Home > Software design >  Endless while loop when input a string to a variable that expected integer value
Endless while loop when input a string to a variable that expected integer value

Time:11-18

My C code as follows

int main() {
    int userInput = 0;

    while (userInput != 4) {
        printf("Enter a number : ");
        scanf("%d", &userInput);
    };
    return 0;
}

This normally work when input a integer value. But when input a string value it not asking again to a input. It goes to a endless loop printing the "Enter a number" phrase. Then, I tried the code as follows.

int main() {
    int userInput = 0;

    while (userInput != 4) {
        userInput = 0;             // reset the userInput value
        printf("Enter a number : ");
        scanf("%d", &userInput);
    };
    return 0;
}

Even that not solved my problem. Why is this happening? How can it be fixed?

CodePudding user response:

You need to free the input buffer from an invalid data. Something like the following.

do
{
    printf("Enter a number : ");
    if ( scanf("%d", &userInput) != 1 )
    {
        scanf( "%*[^\n]" );
        userInput = 0;
    }
} while ( userInput != 4 );

Another approach is to use the function fgets to read the whole string in a character array and then convert it to an integer using strtol and check whether the conversion was successful.

CodePudding user response:

"This normally work when input a integer value. But when input a string value it not asking again to a input."

When you enter an input doesn't match the expected type, i.e. %d for scanf(), and the int type for userInput, the input stream (in this case stdin) is not advanced, which results in repeatedly attempting to convert the same type of data from the same incorrect input.

Additionally, scanf() returns a value indicating how many items were converted successfully. Given that you entered a string, but scanned using the %d format specifier, zero items will have been converted. Checking that value allows programmer to handle incorrect user input gracefully

int num_converted = scanf("%d", &userInput);
if(num_converted != 1) 
{
     //handle error 
     ...
}

As an aside, consider an alternative method using fgets().
The following reads the entire input line into a buffer, eliminates unwanted white space, only then converts the cleaned up buffer to the value...

int main(void) {
    int userInput = 0;
    char inBuf[20] = {0};
    
    printf("Enter a number : ");
    while (fgets(inBuf, sizeof inBuf, stdin)) {
        inBuf[strcspn(inBuf, "\r\n")] = 0;//remove unwanted white space
        userInput = atoi(inBuf);//strtol() would be an alternative
        printf("\n%d entered!\n\nctrl-c to exit\n...Or enter a number : \n", userInput);
    };
    return 0;
}
  • Related