c ++进程文件空行在文件末尾 [英] c++ process file blank line at the end of file

查看:385
本文介绍了c ++进程文件空行在文件末尾的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我使用c ++处理一个文件,我发现在文件结尾总是有一个空行。有人说vim会在文件末尾添加一个'\\\
',但是当我使用gedit时,它也有同样的问题。任何人都能告诉我原因?

when I use c++ to process a file ,I found there is always a blank line in the end of file .Someone says that vim will append an '\n' in the end of file,but when I use gedit,it also has the same question.Can anyone tell me the reason?

1 #include<iostream> 
2 #include<fstream> 
3  
4 using namespace std; 
5 const int K = 10; 
6 int main(){ 
7         string arr[K];
8         ifstream infile("test1");
9         int L = 0;
10         while(!infile.eof()){
11             getline(infile, arr[(L++)%K]);
12         }
13         //line
14         int start,count;
15         if (L < K){
16             start = 0;
17             count = L;
18         }
19         else{
20             start = L % K;
21             count = K;
22         }
23         cout << count << endl; 
24         for (int i = 0; i < count; ++i)
25             cout << arr[(start + i) % K] << endl;
26         infile.close();
27         return 1;
28 }

while test1 file just:
abcd
but the program out is :
2
abcd

(upside is a blank line)


推荐答案

while(!infile.eof())

infile.eof()仅在之后才是真实的。所以循环试图读取多一行,并获得一个空行的尝试。

infile.eof() only is true after you tried to read beyond the end of the file. So the loop tries to read one more line than there is and gets an empty line on that attempt.

这篇关于c ++进程文件空行在文件末尾的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆