1

I am building a basic shell program, and and using a while loop to continually prompt the user and they can put in commands to run. When the user inputs 'exit' I want my shell program to terminate. I use fgets to get the user input, and parse it out into an array cmdArr using strtok.

int j = 0;
char **cmdArr;
char inputsp[128];
char *cmds;

printf("==>");
fgets(inputs, 128, stdin);
cmds = strtok(inputs, " ");
while (j<1) {

    i = 0;
    while (cmds != NULL) {
        cmdArr[i] = cmds;
        cmds = strtok(NULL, " ");
        i++;
    }

    if (strcmp(cmdArr[0], "exit") == 0) {
        printf("exit command passed\n");
        exit(0);
    }
    else {
        printf("==>");
        fgets(inputs, 128, stdin);
        cmds = strtok(inputs, " ");
   }
}

When I type in exit, I have confirmed that cmdArr[0] stores the string "exit" by printfing cmdArr[0]. When I print out the value of strcmp(cmdArr[0], "exit") I always get the value as 10, and I'm nore entirely sure why. I believe they are the same two string, so strcmp should be returning 0 correct?

jpc
  • 129
  • 3
  • 16
  • 2
    10 is the ASCII code for a newline character, so one of your strings has a newline at the end, and the other doesn't. – user3386109 Aug 30 '18 at 20:16

1 Answers1

4

fgets does not remove the newline from strings it reads, even if it's reading from stdin. The return value of strcmp is the difference between the strings at the first place they differ, namely, the newline, which has the ASCII value 10.

Govind Parmar
  • 20,656
  • 7
  • 53
  • 85
  • 2
    That's a common implementation of `strcmp` but the standard doesn't specify it and it is unwise to rely on it. You can count on the sign of the return value: if its zero the strings are equal, if negative the first string comes first in lexicographic order, and if positive, the second string comes first. – rici Aug 30 '18 at 20:21
  • @rici I was describing the behavior that was being exhibited on the OP's system - but you are right. – Govind Parmar Aug 30 '18 at 21:42