How to deal with incorrect C input?

Beginner’s question: Imagine this scenario: I ask the user to enter an integer (get it using scanf), but the user enters a character, because of which the program reaches its end ... but I want to overcome it and make the program tell him that it provided an incorrect input and gave the user another chance to enter input, how can I do this?

+3
source share
6 answers

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 sscanf()adds +/- overflow protection as it sets errno.

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

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

+2

stdio.h, , , , , , , .. , .

C, 70 80- , C, stdio.h , , scanf . , . Curses, ncurses , MS-DOS , . Unix Bill Joy termcap terminfo, . vi termcap curses terminfo.

, , . , , Java Swing ...

+1

scanf - .

0

( *scanf()), ( EOF), .

Or, as a rule, it is better (not least because the error report can report the entire line), use fgets()either getline()to read the entire line, and then use sscanf()other methods to parse this line, and go from there.

0
source

What about:

  int n;
  int c;
  printf("Please enter an integer: ");
  while (scanf("%d", &n) != 1) {
    while (!isspace(c = getchar()));
    ungetc(c, stdin);
    printf("You must enter a valid number. Try again.\n");
    continue;
  }
0
source

You can read user input as a string and then use strtol()to make it an integer.

int main(void)
{
  char* end;
  char number_temp[256];

  int number;  

  while(1)
  {
     puts("Give a number");
     scanf("%s",number_temp);

     number = strtol(number_temp, &end, 10);

     if (end)              //If there is an error the value of *end will be non zero
        printf("try again");
     else
        break;
  }
  return 0;
}
0
source

All Articles