gpt4 book ai didi

c - scanf 没有被调用

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:33:09 26 4
gpt4 key购买 nike

我尝试使用 scanf 多次读取整行,但由于某些原因,它只在第一次有效。第二次循环运行时,编译器忽略了 scanf 函数

这是我的代码:

#include <stdio.h>
int main()
{
char msg[100];
char to[100];
while (1)
{
printf("[]:Msg to ? :");
scanf("%s", to);
printf("[]:Msg: ");
scanf("%99[^.]", msg);
printf("Sending %s\n", msg);
}
return 0;
}

这是我给出的输出:

[]:Msg to ? :Him []:Msg: Hello mister him!. Sending Hello mister

him! []:Msg to ? :[]:Msg:

在这里我期望能够将变量更改为...由于某种原因在 %s 之前添加空格在这里不起作用

最佳答案

问题出在这里:

scanf("%99[^.]", msg);

此语句最多读取 99 个字符,但只能读取到下一个不匹配的字符。现在如果你把

Hello mister him!.

输入缓冲区,你确实有

"Hello mister him!.\n"

在标准输入流缓冲区中。现在,scanf 处理直到(但不包括)点的所有内容,因此点和换行符保留在输入缓冲区中。下一次调用 scanf()

scanf("%s", to);

现在从输出缓冲区中获取点和换行符,它会自动结束要读取的下一行。现在输入缓冲区为空,下面的 scanf 等待下一条消息。

要解决此问题,您可以像这样跳过点和换行符:

scanf("%99[^.]", msg);
getchar(); // Pacman (Eat the dot)

和在其他scanf中使用

// scanf(" %s", to); // Skip the preceding newline

(这是不必要的,正如 H.S. 指出的那样)

请注意,输入消息 >99 个字符的情况尚未得到正确处理。

关于c - scanf 没有被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54216196/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com