0

程序

#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

4

1 回答 1

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;
于 2012-06-12T22:21:01.760 回答