我试图解析一个文本文件。
格式为:
以下是一个示例:" 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
如何将文件中的每一行直接读入变量?我看起来更干净,更容易阅读。
答案 0 :(得分:1)
我发现使用streams
而非string
处理更容易解析这样的行。我经常使用std::istringstream
将我读到的行转换为流进行解析。
也许这个示例代码对您有用吗?
#include <string>
#include <sstream>
#include <iostream>
int main()
{
std::string line = " house1 _rst1,_ab,_aaaa";
std::string house, param1, param2, param3, skip;
std::istringstream iss(line);
iss >> house;
std::getline(iss, skip, '_');
std::getline(iss, param1, ',');
std::getline(iss, skip, '_');
std::getline(iss, param2, ',');
std::getline(iss, skip, '_');
std::getline(iss, param3);
std::cout << house << " : " << param1 << ", " << param2 + ", " << param3 << '\n';
}
修改强>
此外,您可以将流调用连接在一起,形成一个全方位的行解析器,就像这样:
#include <fstream>
#include <string>
#include <iostream>
int main()
{
std::ifstream infile("test.txt");
std::string house, param1, param2, param3;
// this uses ignore() to skip over the '_' characters and std::getline()
// to read up to the ',' delimeters.
while(std::getline(std::getline(std::getline((infile >> house >> std::ws).ignore()
, param1, ',').ignore(), param2, ',').ignore(), param3))
{
std::cout << house << " : " << param1 << ", " << param2 + ", " << param3 << '\n';
}
}
但这可能很难阅读; o)