Search code examples
c++visual-studio-2010stringstreamistringstream

Istringstream doesn't "walk" through the line


I'm trying to read in a feature vector file storing feature vectors in the following way:

(label) (bin):(value) (bin):(value) etc.

like:

-1 5:0.015748 6:0.0472441 7:0.0393701 8:0.00787402 12:0.0314961 13:0.0944882 14:0.110236 15:0.0472441 20:0.023622 21:0.102362 22:0.110236 28:0.015748 29:0.228346 30:0.125984

As you can see it's saved without the bins that have a value of 0 in them.

I tried reading them in with the following code:

int bin;
int label;
float value;
string small_char; -> change to char small_char to fix the problem

if(readFile.is_open())
  while(!readFile.eof()) {
    getline(readFile, line);
    istringstream stm(line);
    stm >> label;
    cout << label << endl;
    while(stm) {
          stm >> bin;
          stm >> small_char;
          stm >> value;
          cout << bin << small_char << value << endl;
    }
    cout << "Press ENTER to continue...";
    cin.ignore( numeric_limits<streamsize>::max(), '\n' );
  } 
}

But for unknown reason the label gets read correctly, the first bin with value as well, but the following bins aren't being read at all.

The output of the above example line is:

-1
5:0.015748
5:0.015748
Press ENTER to continue

The same thing occurs for all lines that are following.

I'm using visual studio 10, if that matters in anyway.


Solution

  • Having tested it myself it seems that you are not using correct types (as well as correct looping condition).

    My test program:

    #include <sstream>
    #include <iostream>
    
    int main()
    {
        std::istringstream is("-1 5:0.015748 6:0.0472441 7:0.0393701 8:0.00787402 12:0.0314961 13:0.0944882 14:0.110236 15:0.0472441 20:0.023622 21:0.102362 22:0.110236 28:0.015748 29:0.228346 30:0.125984");
    
        int label;
        int bin;
        char small;
        double value;
    
        is >> label;
        std::cout << label << '\n';
        while (is >> bin >> small >> value)
        {
            std::cout << bin << small << value << '\n';
        }
    }
    

    Output from this program is:

    -1
    5:0.015748
    6:0.0472441
    7:0.0393701
    8:0.00787402
    12:0.0314961
    13:0.0944882
    14:0.110236
    15:0.0472441
    20:0.023622
    21:0.102362
    22:0.110236
    28:0.015748
    29:0.228346
    30:0.125984
    

    So make sure the variable types are correct, and change the looping to not get double last lines.