fgets - 省略 c 中的最后一行
基本上我的代码有问题 - 这是家庭作业,所以出于明显的原因不想将其发布在这里。如果这样做对我来说真的很重要,那么我将不得不这样做,因为我陷入了困境。
我正在读取 2 个文本文件,它还有一个分隔符,这些值来自命令行,只需假设本例中的分隔符是 xx
File a
a
b
c
File b
d
e
Output should be
axxd
bxxe
cxx
问题是我的代码没有正确执行最后一行
我得到一个输出我
axxd
bxxe
希望你们能够在我不发布所有代码的情况下了解我做错了什么,但我的逻辑遵循这个原则;
while not at the end of the file for files a and b
get a line using fgets from a
create a character pointer and set it to the first occurrence of \n in the line using strchr
if the pointer isn't null
set the pointers value to be the end of line
get the line from b as above
and now write the line from a, the separator and the line from b to file
Basically i am having problems with my code - this is homework so would rather not post it in here for obvious reasons. If it becomes truely important for me to do so then i will have to as i am so stuck.
i am reading 2 text files and it also has a separator , these values come from the command line, just assume that the separator in this case is xx
File a
a
b
c
File b
d
e
Output should be
axxd
bxxe
cxx
the problem is that my code just doesn't do the last line correctly
i get an output of
axxd
bxxe
I hope you guys can gather what i am doing wrong without me posting all my code, but my logic works on this principle;
while not at the end of the file for files a and b
get a line using fgets from a
create a character pointer and set it to the first occurrence of \n in the line using strchr
if the pointer isn't null
set the pointers value to be the end of line
get the line from b as above
and now write the line from a, the separator and the line from b to file
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是您的第一个逻辑问题:
while(!feof(a) && !feof(b))
这意味着如果任一文件已到达末尾,那么您停止处理,即使其他文件中有更多行。
This is your first logic problem:
while(!feof(a) && !feof(b))
This means that if either file has reached the end then you stop processing, even if there are more lines in the other file.
也许您在打印最后一行后不打印换行符?那么它可能根本不会显示在您的屏幕上。请注意,如果原始行有换行符,而文件的最后一行可能没有,则 fgets 仅在缓冲区中放入换行符。
Maybe you don't print a newline after printing the last line? Then it may not display on your screen at all. Notice that fgets only puts a newline in your buffer if the original line had one and the last line of a file might not.