scanf() in C for Keyboard Input

scanf() reads formatted input from the standard input stream. It is declared in <stdio.h>. For most scalar variables, pass the variable address with & so scanf() knows where to store the converted value.

Read an Integer Top ↑

#include <stdio.h>

int main(void) {
    int number;

    printf("Enter an integer: ");
    if (scanf("%d", &number) == 1) {
        printf("You entered: %d\n", number);
    } else {
        printf("Invalid integer input.\n");
    }
    return 0;
}

Example

Enter an integer: 25
You entered: 25

Key point: scanf() returns the number of input items successfully matched and assigned, so checking its return value lets the program detect failed conversion.

Read More Than One Value Top ↑

int age;
double height;

printf("Enter age and height: ");
if (scanf("%d %lf", &age, &height) == 2) {
    printf("Age: %d, Height: %.2f\n", age, height);
}

The values may be separated by whitespace such as spaces or a newline.

Read a Character Top ↑

char ch;
printf("Enter a character: ");
scanf(" %c", &ch);

The leading space in " %c" tells scanf() to skip preceding whitespace before reading the character.

Read a Word into a Character Array Top ↑

char name[50];

printf("Enter your name: ");
scanf("%49s", name);
printf("Hello, %s!\n", name);

For a character array used with %s, the array name already acts as the address, so no & is used. The field width 49 reserves room for the terminating null character in a 50-element array.

%s reads a word and stops at whitespace. For a full line containing spaces, a line-input function such as fgets() is generally a better choice.

Common scanf() Conversions Top ↑

SpecifierDestination type
%dint *
%uunsigned int *
%hdshort *
%ldlong *
%ffloat *
%lfdouble *
%Lflong double *
%cchar *
%scharacter array
%xunsigned integer in hexadecimal notation
%ounsigned integer in octal notation

Basic structure of a C program





plus2net.com



Arjun khatiwada

28-01-2013

Plz ,says me limitation of putchar and getchar functions for reading strings



✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer