简体   繁体   中英

C compare token with string

I read a string from a file composes of two words that I split up with token and want to them compare to my inputs. The first comparison works fine but not the second. The print statement printout the same thing but the check fail. I'm guessing it's due to special end of line character.

if(strcmp(argv[2], token[0]) == 0){
    printf("Input1 match\n");
    printf("%s\n", argv[3]);
    printf("%s\n", token[1]);
    if(strcmp(argv[3], token[1]) == 0)
    {
        printf("Input2 match\n");
    }
}

Edit: There was a \\n character in my second token and using this code to trim the string fix it

void strip(char *s) {
    char *p2 = s;
    while(*s != '\0') {
        if(*s != '\t' && *s != '\n') {
            *p2++ = *s++;
        } else {
            ++s;
        }
    }
    *p2 = '\0';
}

Change your print statements to:

printf("[%s]\n", argv[3]);
printf("[%s]\n", token[1]);

to see if they're really the same. You may well find there's a "hidden" character at the end of the token, such as <space> or \\n .

If it doesn't show up even with that, you can pipe the output through a hex dump program, if you have one available (a) , something like:

./myprog | od -xcb

Then you can examine the output for suspicious characters.


(a) If you're on Windows, gVim has a "convert to hex" on the menu, or you can install CygWin or GnuWin32 tools to get things like od .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM