Expert Novice
Expert Novice

Reputation: 1963

Strange output on using scanf

#include <cstdio>  

int main()  
{  
    int i;
    printf("%d", scanf("%d", &i));
}

Whatever number i input, i get the output:

1

Why is it so?

Upvotes: 5

Views: 370

Answers (3)

BiGYaN
BiGYaN

Reputation: 7159

scanf() returns the number of items read when it succeeds. Here its reading only one number hence the output is 1 every time regardless of the number.

Upvotes: 0

Sadique
Sadique

Reputation: 22813

On success, the scanf function

returns the number of items successfully read.

This count can match the expected number of readings or fewer, even zero, if a matching failure happens. In the case of an input failure before any data could be successfully read, EOF is returned.

Try this as well:

printf("%d",scanf("%d%d",&i,&i));

Upvotes: 11

Tommy
Tommy

Reputation: 1267

You output the result of scanf, which is not the number you enter, but the number of items that are successfully read. The number you enter is stored in i. To output it you would have to write an additional line:

#include <cstdio>  

int main()  
{  
   int i;
   if (scanf("%d",&i) == 1)
       printf("%d", i);
}

Upvotes: 4

Related Questions