-2

When I enter "quit" on my keyboard, the if loop (marked by the comment "here quit is implemented") should return true and the program should end. But strcmp does not return zero. There are no compiler errors. I am not able to identify the problem.

int numInput(){
    char str[10];
    int num;
    char nStr[10];
    char q[4] = "quit"; //Quit

    LAND:
    scanf("%s",&str);
    
    if (strcmp(q,str) == 0){ //Here quit is implemented
        exit(0);
    }else{
        printf(str);
    }

    num = atoi(str);
    itoa(num,nStr,10);
    if (strcmp(nStr,str) != 0){
        printf("Please enter numbers only!\nEnter number here:");
        goto LAND;
    }

    return num;
}
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
  • 1
    `char q[4] = "quit"; ` the string literal `"quit"` is **5** characters long, not 4. Your array is missing the null-terminator – UnholySheep Jun 29 '22 at 12:43
  • Array `q` is not a string because there is no space for the thanks terminator and consequently it cannot be passed legitimately to `strcmp()`. You should pass just `str` and not `&str` to `scanf()`. The type of the latter is `char (*)[10]` but `scanf()` expects a `char *`. – Jonathan Leffler Jun 29 '22 at 12:46
  • `scanf("%s",&str);` ==> `scanf("%9s", str);` But don't use such miserably short strings anyway, and the idoimatic way is `char q[] = "quit";` – Weather Vane Jun 29 '22 at 12:47
  • A side note: using `goto` is considered bad practice. See here: https://stackoverflow.com/questions/46586/goto-still-considered-harmful. – wohlstad Jun 29 '22 at 12:47
  • Grrrr — Grammarly is great, but it has a weird penchant for changing 'null' into 'thanks', at least on my iPhone. My prior [comment](https://stackoverflow.com/questions/72801603/comparing-strings-and-keybord-inputs#comment128589166_72801603) was afflicted by this and I didn't spot it. Grrr! – Jonathan Leffler Jun 29 '22 at 13:52

1 Answers1

2

The char array q doesn't have enough room to store the string "quit".

This string needs 5 characters: 4 for the letters and one for the terminating null byte. And because the array isn't big enough, attempting to use string functions on it causes these functions to read off the end of the array. This triggers undefined behavior.

The array needs to be at least one element larger:

char q[5] = "quit"; 

Or even better:

char q[] = "quit"; 

Which sizes the array to fit the initializer.

Also, this isn't correct:

scanf("%s",&str);

As you're passing a pointer to an array while the %s format specifier expects a char *. This should instead be:

scanf("%s",str);
dbush
  • 205,898
  • 23
  • 218
  • 273