Reputation: 139
Here, I'm trying to get the user's input with getchar(); so the loop runs fine for the first time, but on the second time it's not getting input and moving to the 3rd iteration automatically. I think a newline is doing something here. How can this be resolved?
#include<stdio.h>
void main(){
char input = ' ';
int v, c;
v=c=0;
while(input != '!'){
puts("Enter a char");
input = getchar();
switch(input){
case 'A':
case 'a':
case 'E':
case 'e':
case 'I':
case 'i':
case 'O':
case 'o':
case 'U':
case 'u':
v=v+1;
break;
default:
c = c+1;
}
}
if(v>c)
puts("Vowel wins.");
else if(c>v)
puts("Constant wins.");
else
puts("It's a tie.");
}
Here is the online code in the compiler, you can run yourself directly for ease. https://onlinegdb.com/HyEzo7w-I
Upvotes: 0
Views: 1029
Reputation: 23802
When inserting a character in the command line you are really inserting two characters, it's the character itself and and the newline character(\n
), so the first getchar()
gets the character and the second getchar()
gets the newline character, so it jumps to the third getchar()
.
If you press only enter you can see that it cycles only once since enter is only one newline charater, you can solve this by putting two getchar(), so the second catches the \n
:
while(input != '!'){
puts("Enter a char");
input = getchar();
getchar();
///...
Or create a case in you switch for the newline character.
case '\n': break;
Upvotes: 1