Select specific data in text file to import in 2d array in c++ -
i new c++ programming , trying open text file of information isn't useful me. file looks that:
1
547
troncons
0 1 2 ...
2 2 3 4 5 7 ...
0 4 5 ...
...
so can see each line has different length. want extract first second element (547) tell me number of line after "troncons". after that, number in first column tell me how information distributed in line if it's 0, means second value x , third y, if first value isn't 0 second value x, third number n of y values , n next value y associated x. i'm working integer , trying create array of dimension (i,2) each line (x,y) couple. there other values @ end of each, don't need it.
i got idea on how code should work, don't know how write in c++ since i'm used matlab
get number of line either extracting value in second line or getting total number of line , subtracting 3.
iterate on each line , use conditional statement know if first element 0 or not.
then if it's 0, add second , third value array.
if !=0, third value , iterate on number add in array x second value , y 3+i value.
that's how did in matlab because automatically put text in matrix , easy access index, feel can't c++.
i saw 2 links: how read entire .txt file of varying length array using c++?
reading matrix text file 2d integer array c++
but first 1 used vector or 1 dimensonal array , second 1 took information directly , used static memory.
this should going:
#include <fstream> #include <vector> #include <iostream> #include <string> struct xy { int x; int y; }; using std::ifstream; using std::vector; using std::cerr; using std::endl; using std::string; int main() { vector<xy> data; ifstream input("filename.txt"); if (input.good()) { int skip; string troncons; int numlines; input >> skip; input >> numlines; // 547 input >> tronscons; data.reserve(numlines); // optional, practice (int i=0; i<numlines; ++i) { xy xy; int first; input >> first; if (first == 0) { input >> xy.x; input >> xy.y; data.push_back(xy); } else { int n; input >> xy.x; input >> n; (int j=0; j<n; ++j) { input >> xy.y; data.push_back(xy); } } } } return 0; }
Comments
Post a Comment