0

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.

M.V
  • 29
  • 4
  • 1
    `scanf()` *does* return a value, though you wouldn't know it from the kind of code you find online. – EOF Dec 09 '16 at 06:11
  • have you trie using `break;`? – searchengine27 Dec 09 '16 at 06:11
  • What do you mean by 'when input is not given'? Do you mean you want it to time out if nothing is read within 30 seconds, say? Or if the input line is blank? Or something else? Note that `scanf()` et al don't care in the slightest about newlines or blanks (at least, not when the only formats are `%d`) — it just skips them. – Jonathan Leffler Dec 09 '16 at 06:25
  • 1
    You should enlighten us a little bit more. What do you mean by : _I want to break out of this loop when input is not given when the program runs_ – Prometheus Dec 09 '16 at 06:41
  • Please give some examples of what your use case will be, in what situations we should be breaking out of the loop. – sameera sy Dec 09 '16 at 06:44

1 Answers1

2

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.

Nominal Animal
  • 38,216
  • 5
  • 59
  • 86