0
我試圖解析文本文件。解析格式化文本文件
的格式是:
- 6空格
- 串
- 空間+下劃線+串
- 逗號+下劃線+串
- 逗號+下劃線+串
這裏是一個例子:" house1 _rst1,_ab,_aaaa"
此代碼工作:
#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;
}
我得到house1 : rst1, ab, aaaa
,但我想,以提高使用類似stackoverflow.com/a/3555952/3029422的代碼,但我不知道如何將它應用到我的情況,當我嘗試:
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;
我得到not the expected format
我怎樣才能從文件中讀取每一行直接插入變量?我看起來更乾淨,更容易閱讀。
默認分析僅適用於以空格(空白)分隔的情況。你有用逗號隔開的字段,它會爲你指定一些更多的工作。 – woolstar 2014-09-20 01:23:14