1

I am trying to read values from a file to a vector

std::vector<float> setTimesArray (std::string flName){
    int i=0, dummy=0;
    float temp;
    std::vector<float> pObs;
    std::string line;
    std::ifstream inFile;
    inFile.open(flName.c_str());
    if(!inFile){
        std::cout<<"\n.obs file not valid. Quitting programme...";
        exit(1);
    }
    while(inFile.good()){
        i++;
        getline(inFile, line);
        if(i>=3){ //I don't want first two lines
            std::istringstream in(line);
            in>>dummy;//discards first value in the line
            in>>temp;
            pObs.push_back(temp);
            in.str(""); //discards remaining part of the line
        }        

    }
    return pObs;
    inFile.close();    
}

Problem is, the last value gets repeated. For example, flName had total 975 lines. Thus pObs must be having size=973 (975-2 initial lines). But the size is 974 and I see that the last value is repeating. What mistake have I made?

simonc
  • 41,632
  • 12
  • 85
  • 103
George
  • 91
  • 1
  • 3
  • 8

2 Answers2

4

try:

while (getline(inFile,line))

instead of while(inFile.good()) and remove the getline() call from within the method.

You may also want to change your last two lines of codes to this, as per Daniel Kamil Kozar's suggestion:

inFile.close();
return pObs;
Hanlet Escaño
  • 17,114
  • 8
  • 52
  • 75
0

After the last line, good() is still allowed to return true. It doesn't have to return false until after a failed read. Thus, if it returns true, and then fails the read, your line variable won't take a new value. The correct solution would probably be to correct the bounds checking, but in this case, moving the declaration of line into the scope of you while loop and checking for and empty string should correct the issue.

jpm
  • 3,165
  • 17
  • 24