|
|
scanf to input data from keyboardWe can pass data to our C program by using 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;
}
As you have seen we will get the same data as output what we enter as input.
Entering more than one data
Using one scanf statement we can ask for more than one data to enter
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.
Reading String data
Here is the code to read string data. Note that scanf function will read until it encounters any space or it reaches its limits.
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
| |
| |
|
|
|
|
|