PROGRAM
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main () {
string line,p1,p2,p3;
ifstream myfile ("infile.txt");
if (myfile.is_open())
{
while ( myfile.good() )
{
/*
myfile >> p1 >> p2 >> p3 ;
cout << "p1 : " << p1 << " p2 : " << p2 << " p3 : " << p3 << endl;
*/
getline (myfile,line);
cout << "line : " << line << endl;
}
myfile.close();
}
else cout << "Unable to open file";
return 0;
}
INFILE.TXT
name
param1 = xyz
param2 = 99
param3
param_abc = 0.1
june 2012
输出
line : name
line : param1 = xyz
line : param2 = 99
line : param3
line : param_abc = 0.1
line : june 2012
line :
我想搜索param2并打印其值,即99
答案 0 :(得分:1)
阅读完行后,你可以解析它:
stringstream ss(line);
string token;
if (ss >> token && token == "param2") {
ss >> token; // '='
ss >> token; // value of param2
cout << "param2 is: " << token << endl;
}
}
您应该为读取操作的成功添加更多测试(并且可能是“param2”之后的令牌确实是=
)
如果“param2”的值预期为整数,则可以提取该值而不是最后一个令牌提取:
int val;
ss >> val;