Using the return value from scanf in the C programming language as a check
Solution 1
scanf
will return the number of items assigned. In your case, since the format string contains only %lf
, it will return 1
exactly in the case where you got your double
. The problem with your code is that you first call scanf
inside the loop, which will read the double
off the stream. Then, in your while
condition, you call scanf
again, but there isn't another double
to be read, so scanf
does not do anything.
The way I would write your code would be something like
int no_assigned;
do {
printf("Input?");
no_assigned = scanf("%lf", &input);
} while (no_assigned != 1);
The extra variable is there because it feels to me like the scanf
is code that should be inside the loop, not in the while
condition, but that is really a personal preference; you can eliminate the extra variable and move (note, move, not copy) the scanf
call inside the condition instead.
EDIT: And here's the version using fgets
that's probably better:
double input;
char buffer[80];
do {
printf("Input? ");
fflush(stdout); // Make sure prompt is shown
if (fgets(buffer, sizeof buffer, stdin) == NULL)
break; // Got EOF; TODO: need to recognize this after loop
// TODO: If input did not fit into buffer, discard until newline
} while (sscanf(buffer, "%lf", &input) != 1);
Solution 2
scanf() and friends return the number of input items successfully matched and assigned. No information related to type. But since you've specified lf
in the conversion string, you'll get a double - I think I'm missing your point though.
Solution 3
Just like Michael said, scanf() returns and integer that represents the number of elements suceccesfully read. As far as I can see from the manpage you can't use the return value to verify if what was read is a double or not.
Solution 4
I think this is what you're trying to do:
double input;
do { /* do this as long as it not a double */
printf("Input?");
} while(!scanf("%lf", &input));
Chris_45
Updated on July 17, 2022Comments
-
Chris_45 almost 2 years
How do you use the return value from scanf to make sure it is a double I've got?
double input; do { /* do this as long as it not a double */ printf("Input?"); scanf("%lf", &input); } while(scanf("%lf", &input) != 1); /* this will not work */