Question

So I'm trying to read in from a file. And if there is a '#' in the middle of a line, or anywhere for that matter, I want to ignore the rest of the line, and keep reading. This is what I have:

while(getline(pgmFile, temp))
    {
    istringstream readIn(temp);
    lines++;

    while(readIn >> convert)
    {
        //cout << temp[counter] << endl;
        if (temp.length() == 0 || temp[counter] == '#' || temp[counter] == '\r' || temp[counter] == '\n')
        {}
        else
        {/*cout << temp << endl;*/}
        if(temp.at(counter) == '\n' || temp.at(counter) == '\r')
        {}
        if(convert < 57 || convert > 40)
        {
        pixels.push_back(convert);

        }
    }

For this input file:

P5
4 2 
64

0 0 0 0 # don't read these: 1 1 1 1
0 0 0 0

It should read in the 0's, but nothing after the #.

temp is of type "string", and it's reading in line by line.

Any help is much appreciated!!!

Was it helpful?

Solution

You could cut your string at the first '#' (if it's present) at the time you construct your istringstream. This would let you simplify the rest of your logic by pretending that the '#' is never there:

while(getline(pgmFile, temp))
    {
    size_t pos = temp.find('#');
    istringstream readIn(pos == string::npos ? temp : temp.substr(0, pos));
    lines++;
    ...
    }

Since you read line-by-line, and because the delimiter is discarded, you can safely skip the check for the '\n' character, too: it's not going to be there.

OTHER TIPS

A double getline (one for the line, one for ignoring anything starting at '#'):

#include <iostream>
#include <sstream>

int main() {
    // Ignoring P5
    std::istringstream pgmFile(std::string(
        "4 2\n"
        "64\n"
        "\n"
        "0 0 0 0 # don't read these: 1 1 1 1\n"
        "0 0 0 0\n"));
    std::string line;
    while(getline(pgmFile, line)) {
        std::istringstream line_stream(line);
        std::string line_data;
        if(getline(line_stream, line_data, '#')) {
            std::istringstream data_stream(line_data);
            int pixel;
            // Here I omitted additional error checks for simplicity.
            while(data_stream >> pixel) {
                std::cout << pixel << ' ';
            }
        }
    }
    std::cout << std::endl;
    return 0;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top