Search code examples
cinputscanf

How to deal with wrong input C?


Beginner's question:

Imagine this scenario: I request the user to enter an integer (getting it by using scanf) but the user enters a character; because of that the program reaches its end... but I want to overcome it, and make the program tell him that he has provided invalid input and give the user another chance to enter an input. How can I do that?


Solution

  • Use fgets(), then sscanf() or strtol().

    int number;
    char ch;
    char *Prompt2 = "":
    do {
      printf("%sEnter number :", Prompt2);
      Prompt2 = "Invalid input\n";  // Change Prompt2 
      buffer char[50];
      if (fgets(buffer, sizeof buffer, stdin) == NULL) {
        Handle_EOF();
      }  
    } while (sscanf(buffer, "%d %c", &number, &ch) != 1);
    

    Using strtol() instead of sscanf() adds +/- overflow protection as that sets errno.

      char *endptr; 
      errno = 0;
      long number = strtol(buffer, &endptr, 10);
      if (errno || buffer == endptr || *endptr != '\n') Handle_Error(();
    

    See Read_long() as an example of how to use this a function.