C getchar() Function : C Reference
Contents
getchar() : Reading or Accepting String Character by Character
In C Programming we have many input/output functions that are useful for accepting input from the user. i.e scanf() | gets(). Getchar() function is also one of the function which is used to accept the single character from the user.
Note :
The characters accepted by getchar() are buffered until RETURN is hit means getchar() does not see the characters until the user presses return. (i.e Enter Key)
Syntax for Accepting String and Working :
/* getchar accepts character & stores in ch */ char ch = getchar();
When control is on above line then getchar() function will accept the single character. After accepting character control remains on the same line. When user presses the enter key then getchar() function will read the character and that character is assigned to the variable ‘ch’.
Parameter | Explanation |
---|---|
Header File | stdio.h |
Return Type | int (ASCII Value of the character) |
Parameter | Void |
Use | Accepting the Character |
getchar() Example 1 :
In the following example we are just accepting the single character and printing it on the console -
main() { char ch; ch = getchar(); printf("Accepted Character : %c",ch); }
Output :
Accepted Character : A
getchar() Example 2 : Accepting String (Use One of the Loop)
#include<stdio.h> void main() { int i = 0; char name[20]; printf("\nEnter the Name : "); while((name[i] = getchar())!='\n') i++ ; getch(); }
Explanation of the above Program :
while((name[i] = getchar())!='\n') i++ ;
above while loop will accept the one character at a time and check it with newline character. Whenever user enters newline character then control comes out of the loop.