Home > OS >  Comparing strings and keyboard inputs
Comparing strings and keyboard inputs

Time:06-30

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;
}

CodePudding user response:

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);
  •  Tags:  
  • c
  • Related