我必须接受如下输入,并打印相同的内容(仅句子):
2
I can't believe this is a sentence.
aarghhh... i don't see this getting printed.
数字 2 显示要遵循的行数(此处在此之后 2 行)。 我使用了所有选项 scanf 和 fgets 以及各种正则表达式。
int main() {
int t;
char str[200];
scanf ("%d", &t);
while (t > 0){
/*
Tried below three, but not getting appropriate outputs
The output from the printf(), should have been:
I can't believe this is a sentence.
aarghhh... i don't see this getting printed.
*/
scanf ("%[^\n]", str);
//scanf("%200[0-9a-zA-Z ]s", str);
//fgets(str, 200, stdin);
printf ("%s\n", str);
t--;
}
}
抱歉,我已经搜索了所有相关帖子,但找不到任何答案: 所有版本的 scanf() 都不会产生结果,而 fgets() 只打印第一句话。 提前致谢。
最佳答案
您应该只使用fgets()
。请记住,它将保留换行符,因此您可能需要在阅读该行后手动删除换行符:
if(scanf("%d", &t) == 1)
{
while(t > 0)
{
if(fgets(str, sizeof str, stdin) != NULL)
{
const size_t len = strlen(str);
str[len - 1] = '\0';
printf("You said '%s'\n", str);
--t;
}
else
printf("Read failed, weird.\n");
}
}
关于c - 如何在C中一一获取字符串的输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22501040/