c++seekg

rewinding stream with seekg() C++


I am new in C++. This is a part of a program that actually runs, no mem-leak. It reads a line counting how much doubles per/line there are (aux_d), and if it is equal to dim (dimention) it push_back into the vector.

Read line, and then rewind istringstream fss. But when i print my v_db[i] (vector_database) it only loads zeros into the coordinate class.

coordinates aux_c;
double aux_d;

... do stuff and then

while(std::getline(filestream,line)){
    i=0;
    std::istringstream fss(line);
    while( fss >> aux_d )
        i++;
    if (i != dim){
        std::cerr << "Wrong Tiberium_Base coordinates // "
                  << "Check line -"
                  << lc
                  << "-"
                  << std::endl;
        lc++;          
        continue;
    } 
    fss.seekg(0);
    fss >> aux_c;
    v_db.push_back(aux_c);
    lc++; 
}

So i did this just to make it work.

    std::istringstream fss2(line);
    fss2 >> aux_c;
    v_db.push_back(aux_c);
    lc++; 

I would like to know what the heck is going on here, since i've used seekg with that same purpose before, and didnt have any problem at all (in this program actually). Thanks.


Solution

  • After you are finished with the loop.

    while( fss >> aux_d )
        i++;
    

    fss has failbit set. You need to clear that before you can use the stream.

    while( fss >> aux_d )
        i++;
    
    ...
    
    // Clear the error states of the stream.
    fss.clear();
    
    fss.seekg(0);
    fss >> aux_c;