When setting a character value to specified user input using the getchar() method, the user could potentially decide to not input anything, but still hit the enter key. Is there a way to check to see if the character value is "\n"?
// for example:
printf("input y/n\n");
char inp;
// the user hits enter before entering any value
inp = getchar();
getchar();
while (inp != 'y' && inp != 'n') {
inp = getchar();
getchar();
}
if (inp == 'y') {
printf("+\n");
} else {
printf("-\n");
}
example input/output
case 1
'enter'
yy
results in: +
case 2
'enter'
y
y
yy
results in: +
case 3
'enter'
y
'enter'
y
results in: +
Would anyone be willing to explain these cases? As someone who is new to c, but relatively experienced in java, I'm curious to understand the uses and logic of getchar().
Please remove the second getchar()
// the user hits enter before entering any value
inp = getchar();
//getchar(); // this getchar() is not needed
also in
while (inp != 'y' && inp != 'n') {
inp = getchar();
// getchar(); // this getchar() is not needed
}