user1234392
user1234392

Reputation: 1

reading a file and splitting the line into individual variables

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

OUTPUT

line : name
line : param1 = xyz
line : param2 = 99
line : param3
line : param_abc = 0.1
line : june 2012
line :

i want to search for param2 and print its value i.e. 99

Upvotes: 0

Views: 828

Answers (1)

Attila
Attila

Reputation: 28762

after you read the line, you could parse it:

stringstream ss(line);
string token;
if (ss >> token && token == "param2") {
    ss >> token; // '='
    ss >> token; // value of param2
    cout << "param2 is: " << token << endl;
  }
}

You should add some more testing for the success of the read operations (and maybe that the token after "param2" is indeed =)

If the value of "param2" is expected to be an integer, you could extract that instead of the last token extraction:

int val;
ss >> val;

Upvotes: 1

Related Questions