Open In App

Return values of printf() and scanf() in C/C++

Last Updated : 29 Nov, 2020
Comments
Improve
Suggest changes
Like Article
Like
Report

What values do the printf() and scanf() functions return ? 
 

printf() : It returns total number of Characters Printed, Or negative value if an output error or an encoding error 
Example 1: The printf() function in the code written below returns 6. As 'CODING' contains 6 characters.
 

CPP
// C/C++ program to demonstrate return value
// of printf()
#include <stdio.h>

int main()
{
    char st[] = "CODING";

    printf("While printing ");
    printf(", the value returned by printf() is : %d",
                                    printf("%s", st));

    return 0;
}

Output
While printing CODING, the value returned by printf() is : 6


Example 2: The printf() function in the code written below returns 9. As '123456789' contains 9 characters.
 

CPP
// C/C++ program to demonstrate return value
// of printf()

#include <stdio.h>
int main()
{
    long int n = 123456789;

    printf("While printing ");
    printf(", the value returned by printf() is : %d", 
                                    printf("%ld", n));

    return 0;
}

Output
While printing 123456789, the value returned by printf() is : 9


 


 

scanf() : It returns total number of Inputs Scanned successfully, or EOF if input failure occurs before the first receiving argument was assigned.
Example 1: The first scanf() function in the code written below returns 1, as it is scanning 1 item. Similarly second scanf() returns 2 as it is scanning 2 inputs and third scanf() returns 3 as it is scanning 3 inputs.
 

CPP
// C/C++ program to demonstrate return value
// of printf()

#include <stdio.h>
int main()
{
    char a[100], b[100], c[100];

    // scanf() with one input
    printf("\n First scanf() returns : %d",
                            scanf("%s", a));

    // scanf() with two inputs
    printf("\n Second scanf() returns : %d",
                       scanf("%s%s", a, b));

    // scanf() with three inputs
    printf("\n Third scanf() returns : %d", 
                  scanf("%s%s%s", a, b, c));

    return 0;
}
Input:
Hey!
welcome to
geeks for geeks


Output:
 First scanf() returns : 1
 Second scanf() returns : 2
 Third scanf() returns : 3


 


Next Article

Similar Reads