我是一个C初学者。我注意到使用 fgets 时复制到 str 的最大字符数有些奇怪。部分代码如下:
char reply[10];
printf("Your reply is ->");
fgets(reply,2,stdin);
if(0)
{
REPLY:
printf("Please reply again ->");
fgets(reply,2,stdin);
}
printf("\nreply = %s\n",reply);
if(strncmp(reply,"Y",2) == 0)
{
printf("\nCOOL!! Now let's start the game. Have fun!!!\n");
memset(reply, 0, sizeof(reply));
}
else if(strncmp(reply,"N",2) == 0)
{
printf("\nPlease read through the instruction again.\n");
memset(reply, 0, sizeof(reply));
}
else
{
printf("\nInvalid response\n");
memset(reply, 0, sizeof(reply));
goto REPLY;
}
用户输入类似“asdwq”的内容,这是我的代码中所说的无效响应。然后,输出变得很奇怪,有人可以向我解释下面的输出吗?
Your reply is ->asdwq
reply = a
Invalid response
Please reply again ->
reply = s
Invalid response
Please reply again ->
reply = d
Invalid response
Please reply again ->
reply = w
Invalid response
Please reply again ->
reply = q
Invalid response
Please reply again ->
reply =
Invalid response
Please reply again ->
所以,我的问题是,即使我在 fgets 函数中规定了最大数量“2”,为什么它仍然有剩余的输入。该循环循环多次。看起来整个用户的输入仍然存储在计算机的“某个地方”。它背后的解释是什么?我如何只获取部分输入并丢弃其他输入?
最佳答案
fgets(reply,2,stdin);
最多读入单个字符+1作为终止空字符 fgets()
商店地址:reply[1]
(假设没有输入失败)。一旦用户输入无效输入,输入流中剩余的输入将被后续的 fgets()
消耗。来电。所以你必须删除它们。
一种方法是使用 getchar()
循环中:
while((ch = getchar()) != EOF && ch != '\n');
我说过你的输入读数不寻常且不可读。您需要了解如何使用循环,例如使用 fgets() in a
do-while` 循环。
我还建议您检查 fgets()
的返回值(失败时返回 NULL)。
关于c - 使用 "fgets"时如何仅获取部分用户输入并丢弃其他字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46872615/