-2

I am trying to read values from a .txt file to a vector (which is a member of a class) in C++, but despite the .txt having around 1000 lines, the vector is of size 0. I inserted a 'cout', and I know the file is opened and closed. I'm not sure what I could be doing wrong for the code not to read the contents of the .txt.

#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <cmath>
#include "option_class.h"
using namespace std;
int main(){
double cprice = 0.0;
int i = 0;
string line;
ifstream is;
is.open("/Users/<USER>/Desktop/SPY.txt");
if (!is){
    cout << "Unable to open file" << endl;
    return(0);
}
while(!getline(is, line).eof()){
    is >> cprice;
    option1.price.push_back(cprice);
}
is.close();
cout << "Closing file" << endl;
}
genpfault
  • 47,669
  • 9
  • 68
  • 119
F McA
  • 3
  • 2

1 Answers1

0

Have you tried something simpler:

while (is >> cprice)
{
    option1.price.push_back(cprice);
}

The operator>> will skip whitespace, which includes newlines. There is no need to read a line at a time.

Thomas Matthews
  • 52,985
  • 12
  • 85
  • 144