h101 h101 - 2 months ago 7
C Question

How to check to see if argv[1] ends with a particular character?

Im trying to figure out how to compare the

argv[1]
value with a couple of test cases. I would like to see if
argv[1]
is ending with a particular char value. So far I have the following code:

int main(int argc, char * argv[])
{
char strin[250];
int length;
printf("The argument supplied is %s\n", argv[1]);
strcpy(strin,argv[1]);
length = strlen(strin);
printf("Testing: %c",strin[length]);
if( strin[length] = 'b')
{
printf("b in the input");
}

}


But for some reason whenever I put in any input the print statement triggers. How would I check to see if the last character in the command line argument is equal to the character that I have set it equal to?

zmo zmo
Answer

Basically, all you need is to do is the following:

int main(int argc, char * argv[]) {
    // check if there's an argument to test
    if (0 > argc) {
        // extract the position of the last character
        int last_pos = strlen(argv[1])-1;
        // compare the last character with the character "b"
        if ('b' == argv[1][last_pos]) {
            printf("Hoora! The input ends with b!");
            return 0;
        } else {
            printf("Bummer… The input does not end with b :(");
        }
    } else {
        printf("there's no argument to test!");
    }
}

Now, here's a summary of what's wrong:

int main(int argc, char * argv[])
{
char strin[250];
int length;
printf("The argument supplied is %s\n", argv[1]);

// you're doing a copy from the first argument into the
// variable strin. If argv[1] is 251 characters, you'll
// overwrite memory, and will cause a "buffer overflow".
// Whenever you need to do strcpy of data input by a user
// use strncpy().
strcpy(strin,argv[1]);

// you're extracting the /length/ of the string, not the /position/
// of the last character, so when you're trying to access at index
// length, you'll get data from one character beyond the array.
length = strlen(strin);

// so here you're seeing a random value from the memory of your computer
printf("Testing: %c",strin[length]);

// here you made a mistake and you're assigning the value 'b' to the
// value beyond the allocated memory for the array. Basically: 
// Here be dragons.

// To avoid that mistake, always put the value you're comparing against
// in a comparaison on the Left Hand Side, and the value you're comparing
// on the right hand side. Then the compiler will yell at you!
    if( strin[length] = 'b')
    {
    printf("b in the input");
    }

}