如何输入两个字符串?
#include #include #include int main(void) { char a[1001]; int t,i; scanf("%d",&t); while(t--) { fflush(stdin); gets(a); printf("%d\t",t); puts(a); } return 0; }
输入:
2 die another day. i'm batman.
输出继电器:
1 0 die another day.
预期产出:
1 die another day. 0 i'm batman.
任何人请帮助如何接受多个字符串没有任何错误。 我能够看到进入2后我的获取是将换行作为第一个字符串,然后是第二个正确的字符串。 提前致谢
停止使用stdin
scanf()
来读取输入。 永远不要叫fflush(stdin);
或者,如果你停止使用scanf()
你将不再想要。
使用fgets()
将整行读入适当大小的字符串缓冲区,然后解析所得到的内容。 解析字符串的一个很好的函数是sscanf()
,就像scanf()
只不过它从字符串中读取。
这将更容易,更不烦人,通常更好。 哦,当然永远不会使用gets()
。
像这样(未经测试):
#include #include int main(void) { char line[256]; if(fgets(line, sizeof line, stdin)) { int count; if(sscanf(line, "%d", &count) == 1) { while(count > 0) { if(fgets(line, sizeof line, stdin)) { printf("%s", line); --count; } else break; } } } return EXIT_SUCCESS; }
不要使用fflush(stdin)。 使用getchar()
清除scanf()
之后留下的[enter]字符,
#include #include #include int main(void) { char a[1001]; int t,i; scanf("%d",&t); getchar(); while(t--) { gets(a); printf("%d\t",t); puts(a); } return 0; }
有用。