• Home
  • 1.2 Reading Input from the User

1.2 Reading Input from the User

View Categories

1.2 Reading Input from the User

The scanf() function reads formatted input from the standard input stream. This example reads an integer entered by the user and stores it in a variable.

#include <stdio.h>

int main()
{
    int number;

    printf("Enter a number: ");
    scanf("%d", &number);

    printf("You entered: %d\n", number);

    return 0;
}

Example Output #

Enter a number: 25
You entered: 25

Explanation #

The variable is declared before reading the input:

int number;

The scanf() call reads an integer using the %d conversion specifier:

scanf("%d", &number);

&number supplies the address of number, allowing scanf() to store the input value in that variable.

The value is then displayed using printf():

printf("You entered: %d\n", number);

The format specifier used by scanf() must correspond to the type of the object receiving the input.

Common scanf() Format Specifiers #

Data type Format specifier
char %c
short %hd
int %d
unsigned int %u
long %ld
long long %lld
float %f
double %lf
long double %Lf

For scanf(), the address of the destination object is generally supplied using &. String arrays are an important exception because an array expression is converted to a pointer to its first element.

Powered by BetterDocs

Leave a Reply

Your email address will not be published. Required fields are marked *