\" symbol in an array. The loop conditional never evaluates to true. When I show the contents of the array, the \">\" symbol is there by itself t" />
开发者

while loop conditional never evaluates true when comparing to ">"

I am using a while loop to detect the presence of a ">" symbol in an array. The loop conditional never evaluates to true. When I show the contents of the array, the ">" symbol is there by itself though. In my code,开发者_C百科 this isn't the first call to strtok. This is also only a snippet of the total code. The string to be broken up by strtok is "ls > testfile.txt". Any help would be appreciated.

while (userArgs[k] != ">") {

    k++;

    userArgs[k] = strtok(NULL, " ");
    if(userArgs[k] == ">") {
        break;

    }
    if (userArgs[k] == NULL){
        break;
    }
}


strtok returns a char * so I guess you're trying to compare strings.

You can't compare strings like that in C, use strcmp. What you are doing now is comparing addresses, definitely not what you want.


IF userArgs is of type char then you are comparing a string with a character constant while (userArgs[k] != ">") and if(userArgs[k] == ">") So actually the address of the strings in the binary program file is compared to the character value. Note that the ">" is a string constant and is represented by some address where the string is stored '>' is a character constant and has a value.

IF userArgs is char * then you are comparing the address of the userArgs[i] location in the program stack or heap (if dynamically allocated) with the address of ">" string stored in the program binary and loaded by the OS on the memory. These memory location will vary from time to time and has no relation with the contents of it. To compare the contents of the memories you have to use while (strcmp (userArgs[k], ">") != 0). OR to avoid calling strcmp you might want to do the following while ((userArgs[k][0] != '>') && (userArgs[k][1] == '\0')

The above examples would require change as per your needs.


Use '>' instead of ">". The first one is a character and the second one is a string - or actually a pointer to a character, and comparing pointers clearly isn't what you want.


You are comparing if the address userArgs[k] is the same as the stack address for "<". This is never the case. You would need to match userArgs[k][0] == '>' // note the single quote. but this wrong if the '>' is not preceded by a space.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜