打印从给定字母开始的整条线
我试图打印从给定字母到第二文件的线条,但仅打印1行,然后停止,即使有更多的行以给定字母开头。如何修复它?
#include <stdio.h>
#include <string.h>
int main()
{
FILE* f = fopen("story.txt","r");
char usr;
printf("enter letter: ");
scanf(" %c",&usr);
FILE* f2=fopen("letter.txt","a+");
char buffer[255];
while(fscanf(f, "%[^\n]s", buffer)==1)
if (*buffer == usr)
fprintf(f2, "%s\n", buffer);
return 0;
}
I'm trying to print lines which starts from given letter to second file but it prints only 1 line and then stops, even if there are more lines which starts with given letter. How to fix it ?
#include <stdio.h>
#include <string.h>
int main()
{
FILE* f = fopen("story.txt","r");
char usr;
printf("enter letter: ");
scanf(" %c",&usr);
FILE* f2=fopen("letter.txt","a+");
char buffer[255];
while(fscanf(f, "%[^\n]s", buffer)==1)
if (*buffer == usr)
fprintf(f2, "%s\n", buffer);
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
第二次通过循环,
fscanf(f,“%[^\ n] s”,buffer)
无法扫描任何内容在缓冲区中。这无法超越。使用
fgets()
而不是fscanf()
读取整行。The second time through the loop,
fscanf(f, "%[^\n]s", buffer)
fails to scan anything because the previous call left the\n
character in the buffer. This can't get past that.Use
fgets()
instead offscanf()
to read a whole line.我不会使用
fscanf
读取文本行。I would not use
fscanf
to read line of text.对于初学者,
fscanf
的呼叫中的格式字符串至少不正确,您应该删除字母
s
。另一个问题是,在
fscanf
的呼叫之后,新行字符'\ n'
未读取。因此,fscanf
的下一个呼叫读取一个空字符串。最好使用另一个C函数
fgtes
。但是您需要谨慎使用它。通常,在输入文件中存储的字符串大于数组
buffer
的大小。这意味着您需要使用
fgets
的多个呼叫来读取输入文件中的某些字符串。否则,输出文件将被错误地形成。循环可以看以下方式
For starters the format string in the call of
fscanf
is incorrectAt least you should remove the letter
s
.Another problem is that after such a call of
fscanf
the new line character'\n'
is not read. So the next call offscanf
reads an empty string.It is better to use another C function
fgtes
. But you need to use it with a caution.In general a string stored in the input file can be greater than the size of the array
buffer
.That means that you need to read some strings in the input file using more than one call of
fgets
. Otherwise the output file will be formed incorrectly.The loop can look the following way