getc(stdin) 返回两个字符。有更好的处理方法吗?

4

我目前正在使用getc()循环接收用户输入:

char x;
while (x != 'q')
{    
 printf("(c)ontinue or (q)uit?");
 x = getc(stdin);
}

如果用户输入c,那么循环会执行,可能会在第一轮输入时加上另一个字符(我猜可能是终止符或者换行符?)。我可以通过使用以下方式来防止这种情况:
char toss;
char x;
while (x != 'q')
{    
 printf("(c)ontinue or (q)uit?");
 x = getc(stdin);
 toss = getc(stdin);
}

但我认为这只是一种懒惰的新手处理方式。是否有更清晰的方法使用getc,或者我应该将其作为字符串并使用数组的第一个字符?是否还有其他更干净的方式我甚至没有考虑过?

2个回答

4

我应该将它作为一个字符串使用,并使用数组的第一个字符吗?

没错。

char buf[32] = { 0 };

while (buf[0] != 'q') {
    fgets(buf, sizeof(buf), stdin);
    /* do stuff here */
}

3

您可以忽略空格:

int x = 0;
while (x != 'q' && x != EOF)
{    
 printf("(c)ontinue or (q)uit?");
 while ((x = getc(stdin)) != EOF && isspace(x)) { /* ignore whitespace */ }
}

还要注意,getc()返回的是int而不是char。如果你想检测EOF,这一点很重要,你也应该检查它,以避免无限循环(例如,如果用户在Unix系统上按下Ctrl-D或在Windows上按下Ctrl-Z)。要使用isspace(),你需要包含ctype.h。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接