且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-11-13 23:16:34

而不是告诉你答案的的使用 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