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

Wai*_*ong 4 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");
scanf("%s",comment);
fputs(comment,fp);
Run Code Online (Sandbox Code Playgroud)

Mik*_*ike 21

而不是告诉您不要使用的答案scanf(),您可以只使用Negated scanset选项scanf():

scanf("%99[^\n]",comment); // This will read into the string: comment 
                           // everything from the next 99 characters up until 
                           // it gets a newline
Run Code Online (Sandbox Code Playgroud)

  • 也许``%99 [^ \n]"`在这种情况下?顺便说一句:这确实有副作用,即`\n`没有消耗,仍然在输入缓冲区中.如果这是一个循环,也许使用`"%99 [^ \n]"`(领先空间)? (3认同)

P.P*_*.P. 11

具有%sas格式说明符的 scanf()读取从第一个非空白字符开始的字符序列,直到(1)另一个空白字符或(2)指定字段宽度(例如scanf("%127s",str);- 读取127个字符并将空字节附加为128 ), 以先到者为准.然后在结尾处自动附加空字节.指针通过我的大到足以保存输入的字符序列.

您可以使用fgets读取整行:

fgets(comment, sizeof comment, stdin);
Run Code Online (Sandbox Code Playgroud)

请注意,fgets也会读取换行符.您可能想要从中删除换行符comment.