C- Checking if the first character in the first comand line arguement contains a particular char

StackOverflow https://stackoverflow.com/questions/21978094

سؤال

If the first character of the first argument == "-" then enter the if statement. The error I get is "passing argument 1 of ‘strcmp’ makes pointer from integer without a cast" I have also tried this with fgetc, written a little differently, but still get this error. If I cast it I get a core dump. If the argument contains a dash it would be followed by numbers inside the same argument so I cannot just look at argv[1] as a single char, if I could the condition would be as simple as: if (strcmp(argv[1], "-")==0)

Function

int main (int argc, const char *argv[]){
    const char *test = argv[1];
    if (strcmp(test[0],"-")==0)
        {
          printf("saw there was a dash");
        }
    return 0;}

Thank you for your help

هل كانت مفيدة؟

المحلول

strcmp() is to compare strings, that is, null terminated char arrays. But in here you are comparing two char, this will do:

if (test[0] == '-')

Note the single quotes in '-', that's a char literal.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top