Search code examples
c++outputistringstream

Fivefold output from istringstream


I would like to outout each line after a certain substring is detected. Somehow I get a fivefold output for iss. Here's my code:

    //load all data from txt
        string data;
        std::ifstream infile("SavedData.txt");
        while (std::getline(infile, data)) {
            std::istringstream iss(data);
            string d;
            while (iss >> d) {
                //extract substring
                unsigned firstBracket = data.find("(");
                unsigned lastBracket = data.find(")");
                string coordSynth = data.substr(firstBracket + 1, lastBracket - firstBracket - 1);
                cout << coordSynth << endl;
            }
        }

The output right now is like:

0.0, 45.0, -390.0
0.0, 45.0, -390.0
0.0, 45.0, -390.0
0.0, 45.0, -390.0
0.0, 45.0, -390.0
0.0, 45.0, -314.3
0.0, 45.0, -314.3
0.0, 45.0, -314.3
0.0, 45.0, -314.3
0.0, 45.0, -314.3
etc.

Actually I just want

0.0, 45.0, -390.0
0.0, 45.0, -314.3
0.0, 45.0, -277.3
etc.

And no, in the txt file there aren't duplcates. This file looks like this:

0001(0.0, 45.0, -390.0).png 
0003(0.0, 45.0, -314.3).png 
0007(0.0, 45.0, -277.3).png (and so on...)

Solution

  • Your issue here is that

    unsigned firstBracket = data.find("(");
    unsigned lastBracket = data.find(")");
    string coordSynth = data.substr(firstBracket + 1, lastBracket - firstBracket - 1);
    cout << coordSynth << endl;
    

    Which is the logic to get 0.0, 45.0, -390.0 from 0001(0.0, 45.0, -390.0).png is inside a while loop that you're not even doing anything with. That loop is going to execute 5 times for every line of input (because there are five "sub strings") so you get 5 outputs. All you need to do is get rid of the while loop since you're not doing anything with the individual strings contained in the line. That gives you something like

    int main() 
    {   
        std::string data;
        std::istringstream infile("0001(0.0, 45.0, -390.0).png\n0003(0.0, 45.0, -314.3).png\n0007(0.0, 45.0, -277.3).png\n");
        while (std::getline(infile, data)) {
            std::istringstream iss(data);
            std::string d;
            //extract substring
            unsigned firstBracket = data.find("(");
            unsigned lastBracket = data.find(")");
            std::string coordSynth = data.substr(firstBracket + 1, lastBracket - firstBracket - 1);
            std::cout << coordSynth << std::endl;
        }
    }