6

我想编写一个子程序,用户可以在其中输入他们的评论。我使用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

4 回答 4

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
于 2012-12-05T17:00:23.823 回答
11

使用as 格式说明符的scanf()%s读取从第一个非空白字符开始的字符序列,直到 (1) 另一个空白字符或 (2) 如果指定了字段宽度(例如scanf("%127s",str);-- 读取 127 个字符并将空字节附加为第 128 个字符) ), 以先到者为准。然后在末尾自动附加空字节。传递给我的指针大到足以容纳输入的字符序列。

您可以使用fgets读取整行:

fgets(comment, sizeof comment, stdin);

请注意, fgets 也会读取换行符。您可能希望从comment.

于 2012-12-05T15:28:01.493 回答
3

而不是在标准输入上使用 scanffgets以读取整行。

于 2012-12-05T15:28:38.513 回答
1

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

于 2012-12-05T17:32:05.543 回答