简体   繁体   English

读取 C++ 中文本文件的最后一个空行

[英]Read last empty line of a text file in C++

I try我试试

#include <iostream>
#include <fstream>
#include <vector>

using namespace std;

vector<string> readLines(string filename)
{
    ifstream infile(filename);
    vector<string> v;
    string line;
    bool good;
    do {
        good = getline(infile, line).good();
        if (!good) break; //<---- if exists, or not - is bad
        v.push_back(line);
    } while (good);
    return v;
}

int main() {
    auto v = readLines("test.txt");
    for (auto &line:v)
        cout << ">" << line << endl;
}

If I break loop, no last line in vector, if no break - add empty line although not in file.如果我中断循环,则向量中没有最后一行,如果没有中断-尽管不在文件中,但添加空行。 I want do precisely tests with test file and if exists last empty line is important.我想用测试文件进行精确测试,如果存在最后一个空行很重要。

Solution is simple:解决方法很简单:

#include <iostream>
#include <fstream>

#include <vector>
using namespace std;
vector<string> readLines(string filename)
{
    ifstream infile(filename);
    vector<string> v;
    string line;
    bool readedNewline;
    if (infile.peek() != EOF)
    while(true) {
        readedNewline = getline(infile, line).good();
        v.push_back(line);
        if (!readedNewline) break;
    }
    return v;
}

int main() {
    auto v = readLines("test.txt");
    for (auto &line:v)
        cout << ">" << line << endl;
}

getline().good() returns true if after line is newline char. getline().good() 如果后行是换行符,则返回 true。 Push to vector last not good(), thus I must check if file is not empty (peek())最后推送到向量不好(),因此我必须检查文件是否为空(peek())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM