如何使用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); 

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

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

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

您可以使用fgets读取整行:

 fgets(comment, sizeof comment, stdin); 

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

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

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