C++ Reading file with some information omitted -


i have text file structured this:

g 15324 2353 d 23444  q 23433 32565 

i want store each piece of information variable , contain within vector:

ifstream fin; fin.open("file.txt"); vector<someclass> test; someclass temp; while (fin >> temp.code >> temp.datapoint>> temp.dataleague) {       test.push_back(temp); } 

however, within file third value (temp.dataleague) omitted , left blank. code above not work put garbage within field. how do when it's uncertain if third field contain value or not?

you can try using:

std::istream::getline 

this allow each line inside buffer , process wish.

char buffer[256]; fin.getline(buffer,256); 

you can parse different fields using:

std::string line = std::string(buffer); int index = line.find(' '); if (index>0)     std::cout << "my value is: " << line.substr(0,index); 

with example:

ifstream fin; fin.open("file.txt"); vector<someclass> test; someclass temp; char buffer[256];  while (!fin.eof()) {     fin.getline(buffer,256);     auto line = std::string(buffer);     std::vector<std::string> tokens;     int start = 0, end = line.find(' ');     while (end!=-1)     {         tokens.push_back(line.substr(start,end-1));         start = end +1;         end = line.find(' ');     }     if (start<line.size())         tokens.push_back(line.substr(start));     if (tokens.size()==3)     {         test.code = tokens[0];         test.datapoint= tokens[1];         test.dataleague= tokens[2];         test.push_back(temp);     } } 

Comments

Popular posts from this blog

angular - Ionic slides - dynamically add slides before and after -

minify - Minimizing css files -

Add a dynamic header in angular 2 http provider -