Hello everyone.
Right, it's a simple setup for my program, it reads in a number (as an int) and then does something with it. But, as everyones probably noticed if you type in a character the program 'crashes'. I have the following code:
but I don't understand what the return value from scanf and the new line character have to do with checking for a letter! Is there an easier way of doing this? (I usually use fgets to get an input). Any help with this would be greatly appreciated.Code:#include <stdio.h> void main() { int temp; printf ("Input your number: "); while (scanf("%d", &temp) != 1) { while (getchar() != '\n'); printf ("Try again: "); } printf ("You entered %d\n", temp); }
Cheers,
Chris.



LinkBack URL
About LinkBacks


