How do I use multiple getchar() in C? [GCC Ubuntu]

Hey Guys, I’m Ishan and I am here with a solution to the problem I also faced using getchar() in C. To take input from the user we use getchar(), to take more than one inputs we can use multiple getchar().

But the problem with this is that getchar() takes everything that you do as an input. For example, after entering a value when you hit “ENTER” it takes it as a newline character.

Example code:

#include<stdio.h>
#include<stdlib.h>
int main()
{
char c;
while(1)
{
printf(“nI’m waiting for a character: “);
c=getchar();
printf(“nI waited for the ‘%c’ character”,c );
}
return(0);
}


Output to the above code:

I’m waiting for a character: a
I waited for the ‘a’ character
I’m waiting for a character:      (<== Here the Enter key is taken as input )
I waited for the ‘
‘character


Here the first character is ‘a’ but here it has also taken ENTER key that is the newline character as the second input.  So to solve this I have given the solution below.


Where can you face this getchar() problem?


  1. Using getchar() in a loop. Due to an iterating loop, the input value and the ENTER KEY that is the newline character are two different inputs for the getchar function.


The solution to Multiple getchar() issue:


Just add an extra getchar(); to consume the Enter Key. 

Example code:

#include<stdio.h>
#include<stdlib.h>
int main()
{
char c;
while(1)
{
printf(“nI’m waiting for a character: “);
c=getchar();
getchar();  (<== This helps to consume the Enter Key that is newline character)
printf(“nI waited for the ‘%c’ character”,c );
}
return(0);
}

Output to the above code:

I’m waiting for a character: a
I waited for the ‘a’ character 


Please feel free to comment below if you have any other doubts. 

Leave a Comment