Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/56.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用scanf()扫描包含空格的字符串?_C_Input_Scanf - Fatal编程技术网

如何使用scanf()扫描包含空格的字符串?

如何使用scanf()扫描包含空格的字符串?,c,input,scanf,C,Input,Scanf,我想写一个子程序,用户可以在其中输入他们的评论。 我使用scanf(“%s”,X)让他们输入注释,但它只能将单词存储在字符串中空格之前 如何解决这个问题,以便将整个句子存储到字符串或文件中 我的代码如下: FILE *fp; char comment[100]; fp=fopen("comment.txt","a"); printf("You can input your comment to our system or give opinion to the musics :\n"); sca

我想写一个子程序,用户可以在其中输入他们的评论。 我使用
scanf(“%s”,X)
让他们输入注释,但它只能将单词存储在字符串中空格之前

如何解决这个问题,以便将整个句子存储到字符串或文件中

我的代码如下:

FILE *fp;
char comment[100];
fp=fopen("comment.txt","a");
printf("You can input your comment to our system or give opinion to the musics :\n");
scanf("%s",comment);
fputs(comment,fp);
使用
%s
作为格式说明符,读取一系列字符,从第一个非空白字符开始,直到(1)另一个空白字符或(2)达到指定的字段宽度(例如
scanf(“%127s”,str);
读取127个字符并将空字节追加为第128位),以先到者为准。然后在末尾自动附加空字节。传递给我的指针必须足够大,以容纳输入的字符序列

您可以使用阅读整行内容:

fgets(comment, sizeof comment, stdin);

请注意,FGET也会读取换行符。您可能希望从
注释中删除换行符,而不是在stdin上使用
fgets
,以便阅读整行内容。

而不是告诉您不要使用
scanf()
,您可以选择
scanf()


您可以使用
gets()
getline()
函数从
stdin

读取字符串
%s
不是您想要的。如果您想要添加空格,您想要使用否定的扫描集注意:
scanf(%[^\n]”,如果第一个
字符是
'\n'
,则comment
不会将任何内容扫描到
comment
中,使
comment
未初始化。在这种情况下,可能
%99[^\n]“
中?顺便说一句:这确实会产生副作用,
\n
未被使用,并且仍在输入缓冲区中。可能使用
%99[^\n]”
(前导空格)是否在循环中?并且从C11.开始删除。
getline()
是一个POSIX函数。它在C中不存在
scanf("%99[^\n]",comment); // This will read into the string: comment 
                           // everything from the next 99 characters up until 
                           // it gets a newline