我如何使用扫描scanf函数带空格的字符串()? [英] How can I scan strings with spaces in them using scanf()?
本文介绍了我如何使用扫描scanf函数带空格的字符串()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想写一个子计划中,用户可以输入自己的评论。
我使用 scanf函数(%S,X)
,让他们输入评论,但它只能在字符串中空格键之前存储字。
我怎么能以整个句子存储到字符串或文件,解决这个问题?
我的code低于psented $ P $:
FILE * FP;
焦炭评论[100];
FP =的fopen(comment.txt,一个);
的printf(您可以输入您的评论对我们的系统或给予意见音乐时:\\ n);
scanf函数(%S,评论);
的fputs(评论,FP);
解决方案
而不是告诉你答案的不的使用 scanf()的
,你可以在 的扫描集
选项scanf()的:
scanf函数(%99 [^ \\ n],评论); //这将读取到字符串:评论
//一切从下一个99个字符,直到
//它得到一个换行符
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?
My code is presented below:
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);
解决方案
Rather than the answers that tell you not to use scanf()
, you can just the the Negated scanset option of scanf()
:
scanf("%99[^\n]",comment); // This will read into the string: comment
// everything from the next 99 characters up until
// it gets a newline
这篇关于我如何使用扫描scanf函数带空格的字符串()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文