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 */
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
scanfwill return the number of items assigned. In your case, since the format string contains only%lf, it will return1exactly in the case where you got yourdouble. The problem with your code is that you first callscanfinside the loop, which will read thedoubleoff the stream. Then, in yourwhilecondition, you callscanfagain, but there isn’t anotherdoubleto be read, soscanfdoes not do anything.The way I would write your code would be something like
The extra variable is there because it feels to me like the
scanfis code that should be inside the loop, not in thewhilecondition, but that is really a personal preference; you can eliminate the extra variable and move (note, move, not copy) thescanfcall inside the condition instead.EDIT: And here’s the version using
fgetsthat’s probably better: