[英]How to take inputs for strings one by one in C
I have to take inputs like below, and print the same (only the sentences): 我必须接受如下所示的输入,并打印相同的内容(仅包括句子):
2
I can't believe this is a sentence.
aarghhh... i don't see this getting printed.
Digit 2 shows the number of lines to be followed (2 lines after this here). 数字2显示了要跟随的行数(此后为2行)。 I used all the options scanf and fgets with various regex used.
我将所有选项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--;
}
}
I am sorry, i have searched all related posts, but I am not able to find any answer to this: All versions of scanf() produce no results, and fgets() prints only the first sentence. 抱歉,我已经搜索了所有相关文章,但是我找不到任何答案:所有版本的scanf()均不产生结果,而fgets()仅输出第一句话。 Thanks in advance.
提前致谢。
You should just use fgets()
. 您应该只使用
fgets()
。 Remember that it will keep the linefeed, so you might want to remove that manually after reading the line: 请记住,它将保留换行符,因此您可能要在阅读换行后手动将其删除:
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");
}
}
To make it easier let's say the input is "2\\none\\ntwo\\n". 为了简化起见,假设输入为“ 2 \\ none \\ ntwo \\ n”。
When you start your program, before the first scanf()
the input buffer has all of it and points to the beginning 当您启动程序时,在第一个
scanf()
,输入缓冲区具有所有缓冲区并指向开头
2\none\ntwo
^
After the first scanf()
, the "2" is consumed leaving the input buffer as 在第一个
scanf()
,将消耗“ 2”,而将输入缓冲区保留为
2\none\ntwo
^^
And now you attempt to read everything but a newline ... but the first thing in the buffer is a newline, so nothing gets read. 现在,您尝试读取除换行符以外的所有内容……但是缓冲区中的第一件事是换行符,因此什么也不会读取。
Suggestion: always use fgets()
to read full lines , and then parse the input as you think is better. 建议: 始终使用
fgets()
读取整行 ,然后在您认为更好的情况下解析输入。
To use regex in C you must include regex.h
. 要在C中使用regex,必须包含
regex.h
。 In this case, you do not need regex. 在这种情况下,您不需要正则表达式。 Where you have
"%[^\\n]"
, replace it with "%s"
. 如果您有
"%[^\\n]"
,请将其替换为"%s"
。 Make sure that you include stdio.h
. 确保包含
stdio.h
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.