Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the scanf function return?

Tags:

c

scanf

What is the value returned by scanf when:

int g; int p = scanf("%d", &g);      // Originally: int p = scanf("%d", g); 

I know that the signature of the scanf function is:

int scanf(const char *format, ...) 

What is the int value returned from this function?

like image 372
Rachit Avatar asked May 06 '12 09:05

Rachit


People also ask

What does scanf and printf return?

printf() - printf() returns the number of characters successfully written on the output. It is used to simply print data in the output. scanf() - It returns the number of data items that have been entered successfully.

How does scanf read return value?

scanf() returns the number of items successfully scanned and assigned. If the format string is "%s %d %f %*s%n %d" , it returns 4 if everything works. The %*s suppresses assignment so it isn't counted, and the %n returns an offset and isn't counted. If you get 0, 1, 2, or 3, something went wrong.

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.

What does printf return in C?

The printf() function will return the number of characters printed.


1 Answers

From the man page:

NAME        scanf,  fscanf, sscanf, vscanf, vsscanf, vfscanf          ...  RETURN VALUE        These functions return the number of input items  successfully  matched        and assigned, which can be fewer than provided for, or even zero in the        event of an early matching failure.         The value EOF is returned if the end of input is reached before  either        the  first  successful conversion or a matching failure occurs.  EOF is        also returned if a read error occurs, in which case the error indicator        for  the  stream  (see ferror(3)) is set, and errno is set indicate the        error. 

In your case, scanf() can return 0, 1 or EOF.

like image 137
NPE Avatar answered Sep 30 '22 21:09

NPE