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

时间:2012-12-05 15:22:17

标签: 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);

4 个答案:

答案 0 :(得分:21)

而不是告诉你使用scanf()的答案,你可以只使用scanf()的{​​{3}}选项:

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

答案 1 :(得分:11)

带有%s作为格式说明符的

scanf()读取从第一个非空白字符开始的字符序列,直到(1)另一个空格字符或(2)字段宽度(如果指定)(例如{ {1}} - 读取127个字符并将空字节附加为128th),以先到者为准。然后在结尾处自动附加空字节。指针通过我的大到足以保存输入的字符序列。

您可以使用 fgets 阅读整行:

scanf("%127s",str);

请注意,fgets也会读取换行符。您可能希望摆脱fgets(comment, sizeof comment, stdin);

中的换行符

答案 2 :(得分:3)

而不是scanf在stdin上使用fgets来读取整行。

答案 3 :(得分:2)

您可以使用gets()getline()函数从stdin读取字符串。

相关问题