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
Basic programming structure of C
Arjun khatiwada | 28-01-2013 |
Plz ,says me limitation of putchar and getchar functions for reading strings |