0

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

Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111
  • Have you looked up `std::map` and/or `std::multimap`? – Jerry Coffin Jun 12 '12 at 22:24
  • 1
    [Please don't use `.good()` as a loop condition.](http://stackoverflow.com/questions/21647/reading-from-text-file-until-eof-repeats-last-line) It often produces buggy code (as it did here). In your case, use the return value of `getline`: `while (std::getline(myfile,line)) { std::cout << "line : " << line << "\n"; }` – Robᵩ Jun 12 '12 at 22:55

1 Answers1

1

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;
Attila
  • 28,265
  • 3
  • 46
  • 55
  • Thanks is there anyway to have a search array i.e. param1|param3|June – user1234392 Jun 12 '12 at 22:56
  • Not sure what you mean by "search array", but you could take a loot at `std::map<>`, although you can only have one type for the values (e.g. `string`) – Attila Jun 12 '12 at 22:59
  • i now have the following but it fails on – user1234392 Jun 12 '12 at 23:54
  • sub == param2#include #include #include #include using namespace std; int main () { string line,p1,p2,p3; ifstream myfile ("infile.txt"); if (myfile.is_open()) { while ( myfile.good() ) { getline (myfile,line); /* cout << "line : " << line << endl; */ istringstream iss(line) ; do { string sub ; iss >> sub ; cout << sub << endl ; if (sub == 'param2') { cout << "MATCH : " << line << endl; } } while (iss) ; ----- – user1234392 Jun 12 '12 at 23:56
  • @user1234392 - did you mean `if (sub == "param2")` (note the quote `"` instead of `'` around _param2_) – Attila Jun 13 '12 at 02:17