我想写一个用户可以输入评论的子程序.我使用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);
Run Code Online (Sandbox Code Playgroud)
Mik*_*ike 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
Run Code Online (Sandbox Code Playgroud)
P.P*_*.P. 11
具有%sas格式说明符的 scanf()读取从第一个非空白字符开始的字符序列,直到(1)另一个空白字符或(2)指定字段宽度(例如scanf("%127s",str);- 读取127个字符并将空字节附加为128 ), 以先到者为准.然后在结尾处自动附加空字节.指针通过我的大到足以保存输入的字符序列.
您可以使用fgets读取整行:
fgets(comment, sizeof comment, stdin);
Run Code Online (Sandbox Code Playgroud)
请注意,fgets也会读取换行符.您可能想要从中删除换行符comment.
| 归档时间: |
|
| 查看次数: |
81736 次 |
| 最近记录: |