【问题标题】:How to count the delimiters and re-read lines from istream file?如何计算 istream 文件中的分隔符和重新读取行?
【发布时间】:2019-11-06 00:55:13
【问题描述】:

我有一个基类的单参数构造函数,它以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. std::istream& 中保留以r 开头的行的最后一个字段的“值”

【问题讨论】:

  • @MrSmith42 您的链接与问题无关。 OP 不想计算字符串中的逗号,他想计算一行中的逗号,而不是从输入流中完整提取该行。

标签: c++ algorithm c++11 c++17 istream


【解决方案1】:

怎么样

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-12-07
    • 1970-01-01
    • 1970-01-01
    • 2015-02-03
    • 1970-01-01
    • 2017-09-12
    • 2020-11-21
    • 1970-01-01
    相关资源
    最近更新 更多