2

c ++を使用してファイルを処理すると、ファイルの末尾に常に空白行があることがわかりました。vimはファイルの末尾に「\ n」を追加すると言われていますが、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)
4

2 に答える 2

3
while(!infile.eof())

infile.eof()ファイルの終わりを超えて読み取ろうとした後にのみ真になります。そのため、ループは現在よりも 1 行多く読み取ろうとし、その試行で空の行を取得します。

于 2012-11-22T02:50:28.697 に答える
1

それは順序の問題です。読んで、割り当てて、チェックした後...読み取り、チェック、および割り当てるために、コードを少し変更する必要があります。

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であるかどうかを判断する方法

于 2012-11-22T03:21:48.237 に答える