I have a text file which has data in it in the following format:
string string char int double string
Each field is separated by a tab character. The last string of every line contains multiple words. The file can have up to 50 lines (I am guessing if I can do it for 2 lines I can do it for any number of line). The last line of the file has a keyword announcing the end of the file.
I searched the internet, my notes, and textbook for the past 8 hours to figure this out, but it seems like I'm really dumb (at the moment, at least). It must be something relatively easy, but I can't figure it out.
I have to read the data from the text file in such a manner that I can list them later in different forms (e.g., maybe I want to show all the strings in the first and second column, maybe only the string in the second column and the double, etc.).
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
int main ()
{
vector<string> lines; //vector to hold all the lines
string line; //string to hold intermediary line
ifstream myfile ("example.txt");
if (myfile.is_open()) //if the file is open
{
while ( getline (myfile,line ).good () )
{
getline (myfile,line); //get one line from the file
lines.push_back(line);
/* checking vector size. not what is expected.
only every other line is saved. grrrrr!!!!
*/
cout << "vector size: " << lines.size()<< endl;
}
/* this for loop is here to test if the vector has saved all the
lines from the while above. IT HASN'T. ONLY LINES 2,4,6,8....
ARE SAVED. I DO NOT KNOW WHY!
*/
for (int i=0; i<lines.size() ;i++ )
{
cout << lines[i] << endl;
}
myfile.close(); //closing the file
}
else cout << "Unable to open file"; //if the file is not open output
return 0;
}
If you can give me a BIG HINT on how to do this I would greatly appreciate it. (I probably need more than a hint considering the amount of time I've spent on this and the results, or the lack of, that I came with. Oh, and most of the code above is from the forums. I think I understand the general idea, but, as they say: easy to learn, hard to master.
Thanks a lot!