I currently am stuck on a small part of an assignment I need to do. One requirement of the assignment is
\"Call a function that prompts the user for
scanf()
already processes the input for you according to the format specifier (%d
) so you just need to understand how scanf
works and use it to check and build your function :)
When you write scanf("%d", &a);
the program expects you write an integer because of the %d
specifier, and if an integer is read, the program writes it into variable a
.
But the function scanf
also has a return value, ie, you can do check = scanf("%d", &a);
and check
will have a value of 0 or 1 in this case. This is because the return value records how many values have been successfuly read. If you entered dsfugnodg
there's no number so it would return 0. If you entered 659 32
it would read the 1st value successfully and return 1.
Your function would look something like:
#include
int getAndPrint(char label)
{
int n = 0, val = 0;
do {
printf("Enter a value for %c: ", label);
n = scanf("%d", &val);
if (n == 0) {
printf("Error, invalid value entered.\n");
/* Consume whatever character leads the wrong input
* to prevent an infinite loop. See:
* https://stackoverflow.com/questions/1669821/scanf-skips-every-other-while-loop-in-c */
getchar();
}
} while (n == 0);
printf("%c = %d\n", label, val);
return val;
}
int main()
{
int a, b, c;
a = getAndPrint('a');
b = getAndPrint('b');
c = getAndPrint('c');
printf("a=%d, b=%d, c=%d\n", a, b, c);
}
See also: Scanf skips every other while loop in C