簡體   English   中英

讀取 C++ 中文本文件的最后一個空行

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

我試試

#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;
}

如果我中斷循環,則向量中沒有最后一行,如果沒有中斷-盡管不在文件中,但添加空行。 我想用測試文件進行精確測試,如果存在最后一個空行很重要。

解決方法很簡單:

#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() 如果后行是換行符,則返回 true。 最后推送到向量不好(),因此我必須檢查文件是否為空(peek())

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM