Demha Demha - 1 year ago 98
C Question

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);
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:


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

Answer Source

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 should require some separation, or some non-numeric character between them:

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

This tells scanf() to expect whitespace between the two numbers.

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

if(scanf("%d %d", &num1, &num2) == 2)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download