0

So I wrote this program using coderunner,

#include <stdio.h>

int main()
{
    int num1, num2;

    scanf("%d%d", &num1, &num2);

    if (num1 > num2) 
        printf("The min is:%d\n ", num2);
    else
        printf("The min is:%d\n ", num1);
return 0;   
}

The problem is that the program wont run. It keeps showing this and then it stops after a while:

running

Removing the scanf fixed the issue, I've tried other programs using scanf and it was fine. Any ideas?

DimaSan
  • 12,264
  • 11
  • 65
  • 75
Demha
  • 13
  • 3

1 Answers1

2

How do you expect scanf() to interpret e.g. 123 or 1232 as two integers? Chances are all digits you enter are "eaten" by the first %d, and then scanf() waits for more for the second.

You must use some separation, or some non-numeric character between them:

scanf("%d/%d", &num1, &num2);

This tells scanf() to expect a slash between the two numbers. You could just use whitespace (without any in the format string, as pointed out in comments) too of course.

Also, you should check the return value before relying on the numbers:

if(scanf("%d %d", &num1, &num2) == 2)
{
}
unwind
  • 391,730
  • 64
  • 469
  • 606
  • Is there a way to let the program use two integers with two digits without the user pressing anything? (Like space or enter) – Demha Oct 10 '16 at 08:45
  • @Demha By definition, `scanf` expects input formatted in a specific way, meaning your user will have to know the format you are expecting. If you want to handle arbitrary input, you'll have to use `fgets` with `stdin` and parse the input string with `sscanf`, checking the return value for errors. `scanf` is a kind of restricted combination of these two functions and using them separately you can choose how to handle badly formed input. – djrollins Oct 10 '16 at 09:17
  • @djrollins Thanks for the explanation! – Demha Oct 10 '16 at 09:41
  • `"%d%d"` and `"%d %d"` both allow and neither _expects_ a whitespace between the two numbers. One format or the other gives OP no advantage. One could enter `+123-456` with either format and scan in 2 `int`. – chux - Reinstate Monica Oct 10 '16 at 15:03