C Language: scanf function(Formatted Read)

In the C Programming Language, the scanf function reads a formatted string from the stdin stream.

Syntax

The syntax for the scanf function in the C Language is:




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



Parameters or Arguments

format

Describes the input as well as provides a placeholder to insert the formatted string. Here are a few examples:

Format Explanation Example
%d Reads an integer 10
%f Reads a floating-point number in fixed decimal format 10.500000
%.1f Reads a floating-point number with 1 digit after the decimal 10.5
%e Reads a floating-point number in exponential (scientific notation) 1.050000e+01
%g Reads a floating-point number in either fixed decimal or exponential format depending on the size of the number 10.5

Returns

The scanf function returns the number of characters that was read and stored. If an error occurs or end-of-file is reached before any items could be read, it will return EOF.

Required Header

In the C Language, the required header for the scanf function is:




#include <stdio.h>



Applies To

In the C Language, the scanf function can be used in the following versions:

  • ANSI/ISO 9899-1990

scanf Example

Let's look at an example to see how you would use the scanf function in a C program:




/* Example using scanf by c programming*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, const char * argv[])
{
    /* Define temporary variables */
    char name[10];
    int age;
    int result;

    /* Ask the user to enter their first name and age */
    printf("Please enter your first name and your age.\n");

    /* Read a name and age from the user */
    result = scanf("%s %d",name, &age);

    /* We were not able to parse the two required values */
    if (result < 2)
    {
        /* Display an error and exit */
        printf("Either name or age was not entered\n\n");
        exit(0);
    }

    /* Display the values the user entered */
    printf("Name: %s\n", name);
    printf("Age: %d\n", age);

    return 0;
}




stdio.h Functions





Instagram