文件末尾的 C++ 进程文件空行

c++ process file blank line at the end of file

本文关键字:文件 进程 C++      更新时间:2023-10-16

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

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()仅在您尝试读取文件末尾之后才是正确的。因此,循环尝试读取比实际多一行,并在该尝试中获得一个空行。

这是一个顺序问题,您正在阅读,分配并在检查后...您应该稍微更改一下代码,以便读取、检查和分配:

std::string str;
while (getline(infile, str)) {
    arr[(L++)%K] = str;
}

http://www.parashift.com/c++-faq-lite/istream-and-eof.html

如何在 c++ 中使用 getline() 时确定它是否为 EOF