w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Processing a file line by line and parsing the line to get separate variables

If there are no spaces in the string, then you can ignore the newlines and just extract tokens:

void read_index(std::istream & infile, std::map<long,
std::string> & index_map)
{
    long n;
    std::string token;

    while (infile >> n >> token) { index_map[n] =
std::move(token); }
}

The error checking for opening the file should happen separately, before you call this function. Otherwise your function is doing Too Much.

If you have arbitrary strings, which may include whitespace, you need to use getline:

    for (std::string line; std::getline(infile, line); )
    {
        std::istringstream iss(line);

        long n;
        std::string token;
        if (iss >> n >> std::ws && std::getline(iss,
token))
        {
            index_map[n] = std::move(token);
        }
        else
        {
            // unparsable input line
        }
    }

As you can see, the benefit of line-based processing is that you can also handle invalid lines and skip over those. The first code that was purely token based stops once and for all as soon as it cannot recognize a token.





© Copyright 2018 w3hello.com Publishing Limited. All rights reserved.