如何计算定界符并从istream文件重新读取行?

问题描述 投票:0回答:1

对于基类,我有一个参数的构造函数,该构造函数将std::istream& in作为参数。假设in是一个文件,其字段由逗号分隔:

c, Toyota  , n, 157
r, Jaguar  , u, 246, 0.2
c, Honda   , b, 145

应该从每行中提取每个字段并放置在它们自己的变量中,除了以r开头的行的最后一个字段,该字段应该留在std::istream& in中以在派生类构造函数中使用。

我想知道是否有办法:

  1. 计算一行中的逗号/分隔符的数量
  2. 返回到同一行的开头,并从该行中提取正确的字段
  3. r中保留以std::istream&开头的行的最后一个字段的“值”
c++ algorithm c++11 c++17 istream
1个回答
0
投票

怎么样

class Base {
    std::string first;
    char second;
    int third;
public:
    Base(std::istream& in) { 
        char dummy;
        std::getline(in, first, ",");
        in >> second >> dummy >> third;
    }
};

class Derived : public Base {
    double forth;
public:
    Derived(std::istream& in) : Base(in) {
        char dummy;
        in >> dummy >> forth;
    }
};

std::unique_ptr<Base> read(std::istream& in) {
    std::string which;
    std::getline(in, which, ",");
    if (which == "c") {
        return std::make_unique<Base>(in);
    } else if (which == "r") {
        return std::make_unique<Derived>(in);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.