The C programming language provides different methods and functions in order to get input. This input can be real-time or batch. Also, the input can be provided from different channels like standard input, file, socket, etc. In this tutorial, we will learn how to get input with the getchar() function.
getchar() Function Syntax
Well, the getchar() function has very simple syntax where it does not requires a parameter and returns an integer but this integer stores ASCII character.
int getchar(void)
No parameter and just return value which is the integer representation of the character. The integer value can be found from the ASCII table. For example character a integer representation is 97 and character b integer representation is 98.
Get Single Character From Standard Input
We will start with a simple example where we will get a single character from standard input which is generally a command line, bash shell, or MS-DOS. In the following example, we will get 3 characters with the getchar() function and store these characters in the variables named a,b,c. We will also use the putchar() function in order to print variables a,b,c.
#include <stdio.h>
int main () {
char a;
char b;
char c;
printf("Enter character: ");
a = getchar();
printf("Character entered: ")
putchar(a);
printf("Enter character: ");
b = getchar();
printf("Character entered: ")
putchar(b);
printf("Enter character: ");
c = getchar();
printf("Character entered: ")
putchar(c);
return(0);
}
Get Multiple Character From Standard Input
We can also use the getchar() function in order to get multiple characters inside a loop. We will loop and get a character in every step and put this character into the string named char txt[200] . We will also count on the variable named int counter and increase in every step.
#include <stdio.h>
int main () {
char txt[200];
int counter=0;
while(a!=EOF){
a = getchar();
txt[counter++]=a;
}
return(0);
}
Check Input If End Of Line (EOL)
As we have been used the end of the line in the previous example we will explain End Of Line or EOL with getchar() function usage. EOL is used to set the end of the line with the \n special character. In some cases, we may need to check if the EOL is provided with the Enter key or \n .
#include <stdio.h>
int main () {
char txt[200];
int counter=0;
while((a = getchar()) != '\n' && a !=EOF ){
putchar(a);
}
return(0);
}