Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C compare token with string

Tags:

c

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';
}
like image 714
Danson Avatar asked Feb 16 '26 19:02

Danson


1 Answers

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.

like image 53
paxdiablo Avatar answered Feb 18 '26 08:02

paxdiablo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!