C Input Functions

The input operations are used to read user values (input) from the keyboard. The c programming language provides the following built-in input functions. 

  • scanf()
  • getchar()
  • getch()
  • gets() 
  • fscanf()

scanf() function
 
The scanf() function is used to read multiple data values of different data types from the keyboard. The scanf() function is built-in function defined in a header file called "stdio.h".
The scanf() function has the following syntax...
scanf("format strings", variableName); 

Example
 
#include<stdio.h>
#include<conio.h>

void main(){
   int x;
   printf("\nEnter integer value: ");
   scanf("%d",&x);
   printf("\nYou have entered %d number",x);   
   getch();
}


Output 


 getchar() function
 
The getchar() function is used to read a character from the keyboard and return it to the program. This function is used to read a single character.
To read multiple characters we need to write multiple times or use a looping statement.
 
Example
 
 #include<stdio.h>
#include<conio.h>

void main(){
   char c;
   printf("\nEnter any character : ");
   c = getchar();
   printf("\nYou have entered : %c\n",c);   
  getch();
}
 
Output

getch() function
 
The getch() function is similar to getchar function. The getch() function is used to read a character from the keyboard and return it to the program. This function is used to read a single character. To read multiple characters we need to write multiple times or use a looping statement.  

Example
 
#include<stdio.h>
#include<conio.h>

void main(){
   char c;
   printf("\nEnter any character : ");
   c = getch();
   printf("\nYou have entered : %c\n",c);   

}

 
Output

gets() function
 
The gets() function is used to read a line of string and stores it into a character array. The gets() function reads a line of string or sequence of characters till a newline symbol enters.
 
Example 
#include<stdio.h>
#include<conio.h>

void main(){
   char name[30];
   printf("\nEnter your name: ");
   gets(name);
   printf("%s",name);
   getch();

Output



fscanf() function

The fscanf() function is used with the concept of files. The fscanf() function is used to read data values from a file. When you want to use fscanf() function the file must be opened in reading mode.

 

 



No comments:

Post a Comment