问题
void
read_stdin(trace_t* trace, state_t state, action_t** action_list) {
// initial stage
int c;
while ((c = getchar())!= EOF && c!='#') {
if (my_isalpha(c)==LOWERCASE) {
state[c-ASCII_CODE_LOWER_A] = '1';
}
}
printf("%s\n", state);
char str[2];
fgets(str, 2, stdin);
printf("%s", str);
}
If '#' is the last character I enter in the getchar() loop, fgets() records the newline character from when I press enter and skips to the print statement immediately (which prints the '\n')
I could fix this by adding an additional fgets()(which has to have a string that is longer than 1 char passed to it for some reason?) but is there a more elegant way of solving this?
回答1:
Well, you can use scanf("%*[\n]");
to ignore any number of consecutive newline. Or scanf("%*1[\n]");
for eating only one newline. If any other character is the first one, it is not consumed.
Another option would be to use low-level operations getchar
and ungetc
:
int eat_stdin_newline(void) {
int ch = getchar();
if (ch != EOF && ch != '\n') {
// if it wasn't EOF or newline, push it back...
ungetc(ch, stdin); // must succeed
}
return ch;
}
Then you can call this function wherever you want:
eat_stdin_newline();
来源:https://stackoverflow.com/questions/64533626/using-fgets-right-after-getchar