0
#include <stdio.h>

int main() {
    while (1){
    int a;
    printf("Enter a random integer: ");
    if (scanf("%d", &a) == 1){
        printf("Yeah! You entered an integer number!\n");
    }
    else {
        printf("Error: That is not an integer. Try again!\n");
    }
    }
    return 0;
}

If I run the code, it works fine when I entered an integer. But if I enter a string, I expect an error message but instead, I got an infinite loop of message. How could I modify my code such that if the user enter a string it will just print an error message and ask again.

Jakeyyyy
  • 1
  • 5
  • 2
    scanf may be used to read a file in a known format. When reading user input it is usually better to read a line using fgets and then parse the line. – stark Mar 14 '22 at 15:00
  • "But if I enter a string, I expect an error message" -- It does print the error message that you expect. However, `scanf` does not remove the bad input from the input stream, so the next loop iteration will attempt to process the same bad input again. Therefore, after determining that the input is bad, you must remove the bad input from the input stream. See the duplicate question for further information. – Andreas Wenzel Mar 14 '22 at 15:06
  • 1
    Don't use `scanf` for user input and input validation. It can't be done properly. Read this: http://sekrit.de/webdocs/c/beginners-guide-away-from-scanf.html – Jabberwocky Mar 14 '22 at 15:10
  • 1
    For line-based user input, I recommend that you always use [`fgets`](https://en.cppreference.com/w/c/io/fgets), which reads exactly one line of input. Anything else is confusing. You can then use the function [`strtol`](https://en.cppreference.com/w/c/string/byte/strtol) to convert the string input into an integer. You may want to take a look at my function `get_int_from_user` in the second code snipped of [this answer of mine to another question](https://stackoverflow.com/a/69636446/12149471). I believe it does exactly what you want. It will ask again until the user input is valid. – Andreas Wenzel Mar 14 '22 at 15:17

0 Answers0