Reputation: 1133
I would like to read from a text file and the format of the file is
Method 1
Method 2
Insert 3 "James Tan"
I am currently using ifstream to open the text file and read the items, but when I use >> to read the lines, which is causing the name not to be fully read as "James Tan". Attached below is the code and the output.
ifstream fileInput;
if(fileInput.is_open()){
while(fileInput.good()){
fileInput >>methondName>>value>>Name;
......
Output
methodName = Method, Method, Insert
value = 1, 2, 3 (must be a usigned integer)
Name = James
What is the better way to process the reading of the lines and the contents. I was told about getline. But i understand that getline reads fully as a line rather than a single word by single word.
Next is fstream really fast?. cause, I would like to process 500000 lines of data and if ifstream is not fast, what other options do I have.
Please advice on this.
Upvotes: 0
Views: 789
Reputation: 168626
Method 1
Method 2
Insert 3 "James Tan"
I take it you mean that the file consists of several lines. Each line either begins with the word "Method" or the word "Insert", in each case followed by a number. Additionally, lines that begin "Insert" have a multi-word name at the end.
Is that right? If so, try:
ifstream fileInput("input.txt");
std::string methodName;
int value;
while ( fileInput >> methodName >> value ) {
std::string name;
if(methodName == "Insert")
std::getline(fileInput, name);
// Now do whatever you meant to do with the record.
records.push_back(RecordType(methodName, value, name); // for example
}
Upvotes: 3