简体   繁体   中英

Comparing strings and keyboard inputs

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM