Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to deal with wrong input C?

Tags:

c

input

scanf

beginners 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 it's 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?

like image 997
Medvednic Avatar asked Feb 03 '14 19:02

Medvednic


People also ask

Why is gets not taking input in C?

Never use gets() . It offers no protections against a buffer overflow vulnerability (that is, you cannot tell it how big the buffer you pass to it is, so it cannot prevent a user from entering a line larger than the buffer and clobbering memory).

What is the correct way to take an int input from the user in C?

In C programming, scanf() is one of the commonly used function to take input from the user. The scanf() function reads formatted input from the standard input such as keyboards.

How do you accept multiple input in C language?

Inputting Multiple Values If you have multiple format specifiers within the string argument of scanf, you can input multiple values. All you need to do is to separate each format specifier with a DELIMITER - a string that separates variables.

How do you input a letter in C?

The Syntax for input and output for String is: Input: scanf("%s", stringVariable); Output: printf("%s", stringVariable); Example: C.


3 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 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.

like image 67
chux - Reinstate Monica Avatar answered Oct 23 '22 18:10

chux - Reinstate Monica


The return value of scanf is the number of arguments successfully scanned.

like image 1
Dan Avatar answered Oct 23 '22 16:10

Dan


How 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;
  }
like image 1
Filipe Gonçalves Avatar answered Oct 23 '22 17:10

Filipe Gonçalves