当用户输入大于指定给fgets()
的缓冲区大小时,之后的多余字符似乎存储在输入缓冲区中。当我再次调用fgets()
时,它从输入缓冲区中读取那些多余的字符作为用户输入。示例代码:
int main()
{
char input[3];
int input_int;
while (1)
{
printf("Enter input: ");
fgets(input, sizeof(input), stdin);
getchar();
input_int = atoi(input);
printf("Your input: %d\n", input_int);
if (input_int == 100)
{
break;
}
}
}
示例输出(都在程序的同一个循环中):
Enter input: 12
Your input: 12
Enter input: 150
Your input: 15
Enter input: 32
Your input: 0
Enter input: 52
Your input: 2
Enter input: 8
Your input: 2
Enter input: 1
Your input: 0
我该如何解决这个问题呢?
发布于 2021-02-09 03:42:35
您应该使用更大的缓冲区,但是如果缓冲区中没有'\n'
字符,则可以使用getchar()
使用剩余的字符,fgets不使用换行符,相反,如果有可用的空间,它会保存它。如下所示:
if (strchr(input,'\n') == NULL) /* no occurence of the newline character in the buffer */
{
while (getchar() != '\n')
;
}
https://stackoverflow.com/questions/66112411
复制