Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange output on using scanf

Tags:

c++

c

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?

like image 287
Expert Novice Avatar asked Apr 22 '11 09:04

Expert Novice


People also ask

What is the output of scanf?

The scanf() function returns the number of fields that were successfully converted and assigned. The return value does not include fields that were read but not assigned. The return value is EOF for an attempt to read at end-of-file if no conversion was performed. A return value of 0 means that no fields were assigned.

What does scanf %D &A i ]); mean?

If you look at it in a web browser you'll see the intended C code, which is scanf("%d",&a[i]) &a[i] means the address of the i th element of the array a . So this reads an integer from standard input, and stores it in a[i] .

Why is scanf returning 1?

This is correct, because, scanf() returns number of successfully matched and converted elements. Considering proper input in your case, every time your input passes the conversion, so you get to see the value 1.

Why %d is used in scanf?

The “%d” in scanf allows the function to recognise user input as being of an integer data type, which matches the data type of our variable number. The ampersand (&) allows us to pass the address of variable number which is the place in memory where we store the information that scanf read.


1 Answers

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

like image 175
Sadique Avatar answered Sep 23 '22 15:09

Sadique