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?
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).
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.
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.
The Syntax for input and output for String is: Input: scanf("%s", stringVariable); Output: printf("%s", stringVariable); Example: C.
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.
The return value of scanf
is the number of arguments successfully scanned.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With