Reputation: 55
Im attempting to check if the input has letters in it and if so repeat the scanf function(Specifically after the switch statement at case 1).
Its capable of detecting single characters, if a character is input the variable remains 0. However, if a number and a character are input, it takes the number and ignores the character. This is the main issue.
Wondering possible ways to filter if user inputs letters to ask the user to re-enter a number.
while (true) {
printf("Enter code 1 :");
number = 0;
scanf_s("%d", &number);
if (number == 0) {
// find the new line to recieve new input
while (fgetc(stdin) != '\n');
}
switch (number) {
case 1:
managers = 0;
printf("Managers\n");
while (managers == 0) {
managers == 0;
scanf_s("%lf", &managers);
if (managers == 0) {
managers == 0;
(printf("You have not enterd a number\n")),(fgetc(stdin) == '\n',managers==0, scanf_s("%lf", &managers));
}
}
printf("Managers have this much %.2f.\n", managers);
break;
default:
printf("Invalid entry please enter 1 or 2.");
break;
}
}
}```
Upvotes: 0
Views: 232
Reputation: 7837
Because scanf(3) will not read what it can't decode, it's easier with uncertain input (not produced by a machine) to first read the input, and then scan it with sscanf(3). That gives you a consistent read-evaluate-process loop (tm).
Don't test the arguments to scanf (or any function, really) to determine if it worked or not. Look at the return code. scanf returns the number of arguments it processed, which tells you what kind of success it had.
If you need to, you can add a %n
argument (that you will need to examine) that tells you how many characters were processed. For example, your user could enter 12 dozen eggs
, and scanf would read 12 into managers
, and return 1, indicating success. But there would still be additional unprocessed input that you might want to deal with. By reading the whole line first, and then scanning it, the input stream isn't blocked, and the application can determine what to do with any invalid input.
Upvotes: 0
Reputation: 153348
Is it possible to validate input with scanf?
With good input and some errant input, it is possible to validate, but in general, not possible to validate input with scanf()
.
... or if the result of the conversion cannot be represented in the object, the behavior is undefined. C17dr § 7.21.6.2 10
With scanf_s("%d", &number);
, if the textual numeric input exceeds the int
range, the result is undefined behavior (UB). Possible UB also for scanf_s("%lf", ...);
The best approach is to read a line of user input with fgets()
and then use strtol()
and friends to validate the string.
A good input design details when input is good what should be done with errant input.
Note, OP's code below leads to an infinite loop should fgetc()
return EOF
due to end-of-file on stdin
.
if (number == 0) {
// find the new line to receive new input
while (fgetc(stdin) != '\n');
}
Upvotes: 1