Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using the return value from scanf in the C programming language as a check

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 */
like image 398
Chris_45 Avatar asked Nov 21 '25 08:11

Chris_45


2 Answers

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);
like image 87
JaakkoK Avatar answered Nov 24 '25 00:11

JaakkoK


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.

like image 44
Michael Foukarakis Avatar answered Nov 23 '25 23:11

Michael Foukarakis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!