April 29, 2013

Return Values of printf() and scanf()

16:33 Posted by Unknown No comments
           Most of people who know C Programming knows about printf( ) and  scanf() functions .We start using them when we begin learning C programming just assuming they are standard input and output functions ....but when we  come to learn functions ...sometimes we tend to look down upon these functions and neglect them as we have used them so many times. But that is a mistake.

printf("Let's correct our mistake by reading this Post");
printf("Just skip this post...so many posts are awaiting you");
printf ( ) ?

It  is a useful function defined in standard library functions and is accessible by using  #include<stdio.h>.
    The printf function writes a formatted string to the stdout strem.The behaviour of printf is defined in the ANSI standard.

                    Syntax: int printf(const char *format ,...) 

I'm assuming you all know about format specifiers ..so i'm directly jumping into the return value.
By the syntax we know that the return type is int ...so printf( ) returns an integer always.

What does this return value mean?
If succesful,it returns the number of characters written to the output.
On failure,it returns a negative number.

Let's check with a program:

int a=100;  // the lines with underlines are for Dev C++. Not required for others

It  outputs 1003 where 100 is printed due to printf("%d",a) and 3 is the value returned by the function printf. Here it is three because 100 has three characters. You might want to be careful while using spaces, because it counts them too.

scanf ( ) ?
scanf()  reads formatted input from stdin stream.
Syntax for scanf:  int scanf(const char *format,...);

It returns the number of items read from input... (not characters..)

let's see:
int a,d,c; 
d = scanf("%d %c",&a,&c);
Here i gave inputs as 100 and 10000 .Two items were read successfully, so the output is 2.

Feel free to comment in case of any doubts and we will help you asap. Do checkout other posts which may interest you or use our RANDOM ARTICLE option to view a random post. Be sure to suggest us to a friend if your like our blog. Have a happy reading :)


Post a comment

Please Enter your comment here......