ccoderunner

scanf prevents program from running


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?


Solution

  • 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)
    {
    }