Parsing .txt file for double variable input in C++ -


currently working on snippet input variables in user changes text file used later. storing these in array, , later referencing them opengl.

the input text file looks this.

something = 18.0;

something else = 23.4;

... 6 lines total

//the variable of type ifstream: ifstream patientinput(".../patient1.txt"); double n[6]= {0.0,0.0,0.0,0.0,0.0,0.0}; register int i=0; string line; //check see if file opened:  if (patientinput) printf("patient file opened.\n");  else printf("unable open patient file\n");   while(!patientinput.eof())  {     getline(patientinput,line);     char *ptr, *buf;     buf = new char[line.size() + 1];     strcpy(buf, line.c_str());     n[i]=strtod(strtok(buf, ";"), null);     printf("%f\n",n[i]);     i++;  } //close stream: patientinput.close(); 

right saving values in array initialized not overwriting them later, should when breaking lines tokens. appreciated.

to apply nattybumppo had change:

n[i]=strtod(strtok(buf, ";"), null); 

to:

strtok(buf," ="); n[i] = strtod(strtok(null, " ;"), null); delete buf; 

of course, there lot of other ways without strtok.

here's 1 example:

ifstream input; input.open("temp.txt", ios::in); if( !input.good() )     cout << "input not opened successfully";  while( !input.eof() ) {     double n = -1;     while( input.get() != '=' && !input.eof() );      input >> n;     if( input.good() )         cout << n << endl;     else         input.clear();      while( input.get() != '\n' && !input.eof() ); } 

Comments