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.
#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.
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.
char ch;
printf("Enter a character: ");
scanf(" %c", &ch);
The leading space in " %c" tells scanf() to skip preceding whitespace before reading the character.
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.
| Specifier | Destination type |
|---|---|
%d | int * |
%u | unsigned int * |
%hd | short * |
%ld | long * |
%f | float * |
%lf | double * |
%Lf | long double * |
%c | char * |
%s | character array |
%x | unsigned integer in hexadecimal notation |
%o | unsigned integer in octal notation |
Basic structure of a C program
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.
| Arjun khatiwada | 28-01-2013 |
| Plz ,says me limitation of putchar and getchar functions for reading strings | |