Thursday, 19 September 2013

C++ strTok implementation returning weird characters

C++ strTok implementation returning weird characters

I'm currently working on a string tokenizer in C++ and am getting a
strange result. char *mystrtok(char *str, const char *delim) { char *
LeftOver; bool lastToken; int i=0;
if(str != NULL)
{
LeftOver = str;
lastToken = false;
}else
{
str = LeftOver;
}
for(i = 0; str[i] != '\0'; i++)
{
for(int j=0; delim[j] != '\0'; j++)
{
//If I take out this line then it returns weird characters
cout << "\tstr[" << i <<" ]" << "=" << str[i] << endl;
if(LeftOver[i] == delim[j])
{
str[i] = '\0';
LeftOver = str + i+1;
return str;
}
}
}
if(LeftOver[i] == '\0' && !lastToken)
{
lastToken = true;
return str;
}
return NULL;
}
What's really weird is that if I take out the cout then it returns weird
characters Any idea what could be causing this?
Here's a sample output //input "ls -l -a | wc -c >> myfile"
returned: ls
¢ÆM.¢Æ

No comments:

Post a Comment