Hi :)
I am trying to make a program that reads inputs from different days, saves the dates and other info in a text file and then has the option of reading if needed. Everything is working okay so far, except for the fact that it only reads the first line, and then it stops. I don't know why.
void reader()
{
ifstream comboReader("combo.txt");
string line, num,temp ;
stringstream td ;
float dLine;
float total = 0.0;
int iter = 0,iter0 = 0;
std::vector <float> hours(0);
while(!comboReader.eof())
{
getline(comboReader,line); //take a line from file
comboReader >> temp ; //split the line into two
comboReader >> num ;
td << num ; //load the second value into stringstream td
td >> dLine ; //extract a float
hours.push_back(dLine); //add the double to a vector
iter++ ; //count iterations to make sure program is not overlooping
td.clear(); //empty bit flags
td.str(""); //empty contents of td stringstream object
cout << line << endl; //print line? but it only prints the first line
}
comboReader.close();
cout << "total items in vector: " << hours.size() << endl ; //check
cout << "Iterations: " << iter << endl ; //check
cout << "Test Item 3 Value: " << hours.at(2) << endl ; //check
}
Everything is working properly except for the last line in my while loop which is supposed to simply print out the file as it is.
After line 12, you should never touch comboReader again, yet you do on the next two lines.
Never loop on eof() - it does not work as expected. Specifically, the eof flag is only set when you try to read after getting to the end of the file. Instead, loop on the input operation:
I'm a bit confused about this, is istringstream supposed to replace stringstream?
Will I still be able to use 'num' as a float, because I need to add the values later.
Okay, I deleted line 5 but now I seem to have a problem.
I tried doing hours.push_back(num);
and it's giving me an error because it thinks I'm trying to push a string. How would I be able to make num into a float to push it into the vector if I'm deleting line 5.
dLine was what I was using previously to change the second string into a float, I had no idea I could use istringstream instead. It works great now. :)
I have a question if you can, does istringstream automatically read out every word in a string? Because if not why does the if statement work?
std::istringstream is a derived class of std::istream, and std::cin is also a derived class instance of std::istream. Anything you can do with std::cin, you can do with std::istringstream. The difference is that std::cin reads from standard input (e.g. the console) and std::istringstream reads from a string you supply it.
The same relationship exists for std::ostringstream and std::cout - they are both derived classes of std::ostream.