May 16, 2012

c++ read in file for initialization

two things you should know:

  1. getline read in a single line with "\n" delimiter by default, you can specify the delimiter
  2. >> will automatically skip white space and choose the right type for you

A stardard example

// ini.txt
numberofTest: 100000
kickPerTurn: 20
// code segment
ifstream ini_para("ini_parameters.txt");
if( ini_para.fail() )
cerr <<" failed to open ini_parameters.txt" ;
string dummy_string;
getline(ini_para,dummy_string,':');
         // it's import that you use ':' instead of ":" 
ini_para >> numberofTest;
cout << "numberofTest read as: " << numberofTest <<endl;
getline(ini_para,dummy_string,':');
ini_para >> kickPerTurn;
cout << "kickPerTurn read as: " << kickPerTurn <<endl;
     
        ini_para.close();
A similar discussion could be found example on cplusplus.com.


No comments: