views:

661

answers:

3

How do I make sure I've got a double and not something else?

int main() {
    int flagOk = 0;
    double number;
    while(!flagOk) {
     printf("Put in a double");
     scanf("%lf", &number);
     if(number == "%lf"); //this want make sure
     flagOk = 1;
    }
}
+8  A: 

Check the return value from scanf(); it tells you how many conversions were successful.

In the context, if the conversion fails, you get 0; if it succeeds, you get 1.

Error recovery needs to be thought about. I usually find it easier to read a line of data using fgets() - and never gets()! - and then process it with sscanf(). It is easy to discard the erroneous data if the conversion fails.

Jonathan Leffler
How do I check the return value from scanf?
Chris_45
Check return value from scanf with, for example, `if (scanf("%lf", `.
pmg
A: 

You probably want a code fragment more like this:

double number;
do {
    printf("Enter a double: ");
    scanf("%*c"); // burn stdin so as not to buffer up responses
} while (1 != scanf("%lf", &number));

However as Jonathan has pointed out, some better line-by-line parsing may be better. Scanning directly from stdin this way isn't intuitive to the user.

Matt Joiner
Ok whats that scanf("%*c"); all about?
Chris_45
It reads the next character - possibly a newline, possibly something else - without actually assigning it to anything.
Jonathan Leffler
Ok, thanks.....
Chris_45
chris_45 it flushes stdin, fflush() won't do this as expected...
Matt Joiner
A: 
Randall Sawyer