c++ - 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 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 search param2 , print value i.e. 99

after read line, 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 more testing success of read operations (and maybe token after "param2" indeed =)

if value of "param2" expected integer, extract instead of last token extraction:

int val; ss >> val; 

Comments

Popular posts from this blog

django - How can I change user group without delete record -

java - Need to add SOAP security token -

java - EclipseLink JPA Object is not a known entity type -