HyunYoung Go
HyunYoung Go

Reputation: 103

scanf integer with %ld %ld is not work correctly

I'm using gcc 4.4.7.

When I run below simple logic(C lang).

Then inputted '1 2'.

 int var1 = 0; 
 int var2 = 0;

 if(!scanf("%ld %ld",&var1, &var2))
 {
    printf("--- ERROR\n");
 }
 else
 {
    printf("--- var1  [%ld] \n", var1);
    printf("--- var2  [%ld] \n", var2);
 }

Result : --- var1 [0] --- var2 [2]

I already know %ld works for long int. What I realy want to know is how does scanf working in detail. This happens when I try to scan 2 or more numbers.

Upvotes: 1

Views: 1284

Answers (1)

gsamaras
gsamaras

Reputation: 73366

The format specifier %ld is for long int (and %lld for long long int).

int should be matched with the %d format specifier. Using a format specifier that does not agree with the variable types leads to Undefined Behavior.

Don't check the return value from scanf with the ! operator but with the number of conversions expected instead, like this:

if(scanf("%d %d", &var1, &var2) != 2)
  printf("--- ERROR\n");

Further Reading
What happens when I use the wrong format specifier?

Upvotes: 7

Related Questions