【发布时间】:2017-08-03 01:28:14
【问题描述】:
用户输入“1”或“0”选项以继续使用 fgets() 获取字符串。因此,当用户输入选项时,fgets 从控制台读取它。我将它存储在另一个变量中。但是 fgets 获得选择并将其存储在消息中。收到选择后,我尝试使用 fflush(stdin)。请帮帮我。
int main() {
int choice=1;
char *message;
int i=0;
while (choice == 1) {
fflush(stdout);
printf("Enter the message: ");
fflush(stdout);
message = fgets(message,200,stdin);
while (message[i]!='\n') {
i++;
}
message[i] = '\0';
send_message(message);
printf("\nType '1' to continue or '0' to quit: ");
scanf("%d",&choice);
fflush(stdin);
}
}
【问题讨论】:
-
fflush(stdin);是未定义的行为。为什么不只是阅读换行符,然后一次又一次地阅读一行?或者,只需对所有内容使用 fgets 并解析 int。 stackoverflow.com/questions/2979209/using-fflushstdin -
char *message; ... fgets(message,200,stdin);将未初始化的message传递给fgets()。您希望函数如何处理此类数据? -
告诉用户输入
y或n,然后尝试用"%d"读取整数不会带来快乐。即使您没有,您的用户也会感到困惑。您的另一个主要问题似乎是scanf()leaves newlines behind。 -
@JonathanLeffler 已编辑。谢谢!