如何使用 scanf() 扫描包含空格的字符串? [英] How can I scan strings with spaces in them using scanf()?
本文介绍了如何使用 scanf() 扫描包含空格的字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想编写一个子程序,用户可以在其中输入他们的评论.我使用 scanf("%s", X)
并让他们输入注释,但它只能存储字符串中空格键之前的单词.
I want to write a sub-program in which a user can input their comment.
I use scanf("%s", X)
and let them input a comment, but it can only store the word before a space bar in the string.
如何解决这个问题,以便将整个句子存储到字符串或文件中?
How can I solve this problem in order to store a whole sentence into a string or a file?
我的代码如下:
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 :
");
scanf("%s",comment);
fputs(comment,fp);
推荐答案
而不是告诉你不要使用 scanf()
的答案,你可以否定扫描集 scanf()
选项:
Rather than the answers that tell you not to use scanf()
, you can just the the Negated scanset option of scanf()
:
scanf("%99[^
]",comment); // This will read into the string: comment
// everything from the next 99 characters up until
// it gets a newline
这篇关于如何使用 scanf() 扫描包含空格的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文