Reputation: 60
So I'm trying to implement a stack in c. I wrote all the functions, but I have a problem with fgetc function. So here's a part of my code:
while (1) {
printf("Choose an option: \
\n 1 Push \
\n 2 Pop \
\n 3 Top \
\n 4 Print \
\n 5 Exit\n");
option = fgetc(stdin);
opt = ctoi(option);
while ( opt < 1 || opt > 5 ) {
printf("Wrong entry, let's try again: \n");
option = fgetc(stdin);
opt = ctoi(option);
}
switch ( opt ) {
case 1: push(&stack, fgetc(stdin)); break;
case 2: pop(&stack); break;
case 3: top(&stack); break;
case 4: print_stack(&stack); break;
case 5: return 0; break;
default: printf("impossible"); break;
}
}
ctoi is a function i wrote that converts char to int. The problem is, if i enter, for exmple:
1
and press enter, the first call of the function will ask me for input, but the second one(inside the push function call) will automatically forward '\n' as an argument, and I would like o ignore '\n' and ask me for an input again. Is this possible? Thanks!
Upvotes: 0
Views: 48
Reputation: 16117
Each time Enter is hit, a '\n' is left in stdin. You can ignore it by #include <ctype.h>
and writing
do {
option = fgetc(stdin);
} while(isspace(option));
I cannot, because the second call is an argument of another function.
Well, you can also write your own function for input:
int getOption(void)
{
int option;
do {
option = fgetc(stdin);
} while(isspace(option))
return option;
}
Upvotes: 5