I'm trying to parse a text file.
The format is :
- 6 spaces
- string
- space + underscore + string
- comma + underscore + string
- comma + underscore + string
Here is an example : " house1 _rst1,_ab,_aaaa"
This code is working :
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main() {
ifstream infile("test.txt");
string line;
while (getline(infile, line)) {
string house, param1, param2, param3;
size_t posP1, posP2, posP3;
// trim leading whitespaces
while (isspace(line.at(0)))
line = line.substr(1,line.length() - 1);
posP1 = line.find(" _");
house = line.substr(0, posP1);
posP2 = line.find(",_", posP1 + 2);
param1 = line.substr(posP1 + 2, posP2 - posP1 - 2);
posP3 = line.find(",_", posP2 + 2);
param2 = line.substr(posP2 + 2, posP3 - posP2 - 2);
param3 = line.substr(posP3 + 2, line.length() - 2);
cout << house << " : " << param1 << ", " << param2 + ", " << param3 << endl;
}
return 0;
}
i get house1 : rst1, ab, aaaa
, but I would like to improve the code using something like stackoverflow.com/a/3555952/3029422, but I do not know how to apply it to my case, when I try :
ifstream infile("test.txt");
string line;
while (getline(infile, line)) {
string house, param1, param2, param3;
istringstream iss(line);
if (!(iss >> house >> param1 >> param2 >> param3))
cout << "not the expected format" << endl;
else
cout << house << " : " << param1 << ", " << param2 + ", " << param3 << endl;
I get not the expected format
How can I read each line from the file directly into the variables ? I looks more clean and easy to read this way.