I have a code written in c:
int num1,num2;
while(1)
{
scanf("%d",&num1);
scanf("%d",&num2);
}
I want to break out of this loop when input is not given when the program runs.
I have a code written in c:
int num1,num2;
while(1)
{
scanf("%d",&num1);
scanf("%d",&num2);
}
I want to break out of this loop when input is not given when the program runs.
You asked, and that is much, much more than I normally see.
Try the following:
int num1, num2;
while (1) {
if (scanf(" %d %d", &num1, &num2) != 2) {
/* End of input (Ctrl+D)? */
if (feof(stdin))
break;
/* No, just invalid input. */
fprintf(stderr, "That was not two integer numbers. I'm out.\n");
break;
}
printf("You supplied %d and %d.\n", num1, num2);
}
You see, the scanf family of functions returns the number of successful conversions. Above, if scanf()
does not read and convert two integers, we check if it failed because it encountered end of input (if it did, then feof(stdin)
is true). Otherwise, it must have failed because the input was something else. We cannot retry, because the unparseable input is still unread -- the next try would just fail the same way. (There are ways to consume the bad input, but I'd just read the input line-by-line, and try and parse (or reject) each line instead.)
I see so much code that never checks the return value of any of the scanf family of functions, and so many questions on the behaviour caused by it (incorrect input causing endless loops, maybe out of memory situations, buffer overruns), that it sometimes feels futile to even read a question related to any scanf() function. But, you asked. (And, the other you, reading this question and answer but not being the OP, are interested in the matter.) That is good. That means, perhaps someone actually cares about writing robust programs that don't get into a hissy panic whenever the input diverges just a bit from the expected. I want robust programs.