简体   繁体   中英

How to count the delimiters and re-read lines from istream file?

I have a one-argument constructor, for a base class, that takes a std::istream& in as a parameter. in is suppose to be a file with fields separated by a comma:

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

Each field is supposed to be extracted from each line and placed in their own variable, except for the last field of the line leading with r , which is supposed to stay in std::istream& in to be used in the derived class constructor.

I want to know if there is a way that I can:

  1. Count the number of comma/delimiters in a line
  2. Go back to the start of that same line and extract the correct fields from the line
  3. Leave the "values" of the last field of lines leading with r , in the std::istream&

How about

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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