简体   繁体   中英

Make getline() read the right line

I have 3 functions that use getline. The first function checks which of the 2 functions to call depending on the first character of a line.

iMessage* getMessage(std::ifstream& ifs, char n) {

    iMessage* msg;
    std::string line;

    std::getline(ifs, line, n);

    if (line[0] == 'T') {

        msg = new Twitter(ifs, n);
    }

    else if (line[0] == 'e') {

        msg = new eMail(ifs, n);
    }

    else msg = nullptr;

    return msg;
}

And in the twitter / email constructors:

eMail::eMail(std::ifstream& ifs, char n) {


    std::string a;

    std::getline(ifs, a, n);

    //do stuff
}

Twitter::Twitter(std::ifstream& ifs, char n) {

    std::string a;

    std::getline(ifs, a, n);
    //do stuff
}

The problem is that the constructors are always reading the first line of the file. How do I make it so the constructors are reading the same line as the getMessage() function?

getMessage doesn't need to read an entire line to do its job. It can look at just the first character.

In fact, there's a function to look at the first character without removing it from the stream: peek() .

So the whole thing is as simple as

iMessage* getMessage(std::ifstream& ifs, char n)
{
    switch (ifs.peek())
    {
        case 'T': return new Twitter(ifs, n);
        case 'e': return new eMail(ifs, n);
        default:  return nullptr;
    }
}

but the return type should be std::unique_ptr<iMessage> . std::unique_ptr is very helpful for preventing memory leaks.

In getMessage you can restore the file position after reading the line:

std::streampos pos = ifs.tellg();
std::getline(ifs, line, n);
ifs.seekg(pos);

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