scanf()
function. Once executed our program will wait for the user inputs once it came across any scanf function during program execution. Let us enter an integer value and then display the same value by using printf function.
#include <stdio.h>
int main(void){
int num;
printf("Enter a number ");
scanf("%d",&num);
printf(" You entered %d", num); // printing outputs
return 0;
}
While using scanf() , before using the variable we will use & ( ampersand ) to indicate to store the data in address of the variable. See the &num
to say store the input data in address of our variable num.
int main(void){
int num1,num2; // declaring variables as integers
printf("Enter the two numbers ");
scanf("%d %d",&num1,&num2); // Enter two numbers
printf(" Two numbers are %d,%d " ,num1, num2); // printng outputs
return 0;
}
Note that after entering first number we have to press Enter and then write the second number.
int main(void){
char name[30];
printf("Enter your name ");
scanf("%s",name);
printf(" Welcome Mr %30s", name); // printing outputs
return 0;
}
We will read more on scanf in our string handling section for handling other type of data.
%c - a single character
%d - a decimal integer
%e - floating point value
%f - floating point value
%g - floating point value
%h - short integer
%i - floating point value
%o - an octal intger
%s - read a string
%u - unsigned decimal integer
%x - read a hexadecimal integer
%[..] - string of words
With the above list we can prefix these chars in some cases
h for short integers
l for long integers or double
L for long dobule
This example demonstrates how to use scanf() to read an integer input from the user.
#include <stdio.h>
int main() {
int num;
printf("Enter an integer: ");
scanf("%d", &num);
printf("You entered: %d\n", num);
return 0;
}
Output:
Enter an integer: 25
You entered: 25
---
This example demonstrates how to use scanf() to accept multiple inputs in a single line.
#include <stdio.h>
int main() {
int age;
float height;
printf("Enter your age and height: ");
scanf("%d %f", &age, &height);
printf("You entered - Age: %d, Height: %.2f\n", age, height);
return 0;
}
Output:
Enter your age and height: 25 5.8
You entered - Age: 25, Height: 5.80
---
This example shows how to use scanf() to read a single character input.
#include <stdio.h>
int main() {
char ch;
printf("Enter a character: ");
scanf(" %c", &ch); // Note the space before %c to handle leftover newlines
printf("You entered: %c\n", ch);
return 0;
}
Output:
Enter a character: A
You entered: A
---
This example reads a string using scanf() and demonstrates the proper handling of spaces in the input.
#include <stdio.h>
int main() {
char name[50];
printf("Enter your name: ");
scanf("%49s", name); // Limit input to avoid buffer overflow
printf("Hello, %s!\n", name);
return 0;
}
Output:
Enter your name: John
Hello, John!
Arjun khatiwada | 28-01-2013 |
Plz ,says me limitation of putchar and getchar functions for reading strings |