【发布时间】:2016-06-21 02:20:43
【问题描述】:
如果我先读取字符串值然后读取 int 值,它会起作用。
我尝试使用函数gets 而不是scanf,因为gets 让我可以在同一行中读取多个单词。
我也试过fgets,但也有同样的问题。
我使用的是 cygwin 32 位编译器版本 2.874。我使用代码块 ide 13.12。
#include <stdio.h>
#include <stdlib.h>
int main() {
int i;
char s[10];
printf("Value int:\n");
scanf("%d",&i);
printf("%d\n",i);
printf("Value string:");
fflush(stdin);
gets(s);
printf("%s\n",s);
getchar();
return 0;
}
【问题讨论】:
-
你不应该使用 gets 。改用 fgets ==> fgets(s, 10, stdin);或 scanf ==> scanf("%9s", s);
-
gets不是标准的(不再),每个工具链都应该以一种或另一种方式对你大喊大叫。 永远不要使用它!而fflush(stdin)调用未定义的行为。也不要使用它! -
scanf如果使用正确,也可以在一行中读取多个单词。而且你用的是哪个IDE无关紧要,编译器可能会担心,cygwin不是编译器。 -
请参阅Why the
gets()function is to dangerous to be used,了解为什么不应该使用它以及有哪些替代方案。您还需要检查返回结果。您应该查看Usingfflush(stdin),讨论为什么要谨慎使用。
标签: c