scanf function(Formatted Read) in C Language – example and detail

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

Syntax

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

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

Parameters or Arguments

format Describes the input as properly 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 variety with 1 digit after the decimal 10.5 %e Reads a floating-point quantity in exponential (scientific notation) 1.050000e+01 %g Reads a floating-point quantity in either constant decimal or exponential layout depending on the measurement of the variety 10.5

Returns

The scanf characteristic returns the quantity of characters that was once study and stored. If an error takes place or end-of-file is reached earlier than any gadgets 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 feature can be used in the following versions:

ANSI/ISO 9899-1990

scanf Example

Let’s seem at an instance to see how you would use the scanf feature in a C program:

/* Example using scanf by http://TechOnTheNet.com */

#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;
}

Similar Functions

Other C functions that are similar to the scanf function:

fscanf function sscanf function

See Also

Other C functions that are noteworthy when dealing with the scanf function:

fprintf feature printf feature sprintf function vfprintf characteristic vprintf function vsprintf characteristic