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);
}
如果“#”是我在 getchar() 循环中输入的最后一个字符,则 fgets() 会记录我按 Enter 键时的换行符,并立即跳到打印语句(打印“\n”)
我可以通过添加一个额外的 fgets() 来解决这个问题(由于某种原因,它必须有一个长于 1 个字符的字符串传递给它?)但是有没有更优雅的方法来解决这个问题?
嗯,你可以使用scanf("%*[\n]");
忽略任何数字连续的换行符。或者scanf("%*1[\n]");
仅供食用one新队。如果任何其他字符是第一个字符,则不会消耗它。
另一种选择是使用低级操作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;
}
然后你可以在任何你想要的地方调用这个函数:
eat_stdin_newline();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)