#include <stdio.h>
#include<stdlib.h>
#include <string.h>
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 后,我能够看到我的 gets 将换行符作为第一个字符串,然后正确地作为第二个字符串。 提前致谢
最佳答案
停止使用 stdin
的 scanf()
读取输入。永远不要调用 fflush(stdin);
,但如果您停止使用 scanf()
,您将不再需要。
使用 fgets()
读取整行放入适当大小的字符串缓冲区,然后解析您得到的内容。一个很好的解析字符串的函数是 sscanf()
这就像 scanf()
只是它从字符串中读取。
这会更容易,更少烦人,而且通常会更好。哦,当然从不使用gets()
。
像这样(未经测试):
#include <stdio.h>
#include <stdlib.h>
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;
}
关于c - 如何输入两个字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23135602/