Using getline to extract information and store them in a datatype in c++
Here's a code that I wrote which isn't comple开发者_如何学编程te.
string line;
ifstream fp ("foo.txt");
if (fp.fail()){
printf("Error opening file %s\n", "foo.txt");
return EXIT_FAILURE;
}
unsigned int lineCounter(1);
while(getline(fp, line)){
if(lineCounter == 1){
lineCounter++;
} // to skip first line
else{
// find and extract numbers
}
}
The foo.txt file looks like this.
x0,x1,y0,y1
142,310,0,959
299,467,0,959
456,639,0,959
628,796,0,959
Basically, numbers are x and y coordinates.All I need is to extract the numbers in a datatype that is easy to read and be able to access them like a matrix. It should store as 4 containers, having [142, 310, 0, 959], [299, 467, 0, 959]...and so on for the 4 lines.
I tried find() function, but I'm not sure how to use that correctly to put them in the datatype.
How do I extract only the numbers and store them in a datatype that I can move around in and access them like arrays?
To read 4 numbers seporated by comma do this;
std::string line;
std::getline(file, line);
std::stringstream linestream(line);
int a,b,c,d;
char sep; // For the comma
// This should work even if there are spaces in the file.
// The operator >> will drop leading white space
// Then read the next type
// For int object will read an integer from the stream
// For char object will read the next char (after dropping leading white space)
linestream >> a >> sep >> b >> sep >> c >> sep >> d;
Building on @Martin's answer:
std::string line;
std::getline(file, line);
std::stringstream linestream(line);
int a,b,c,d;
char sep; // For the comma
// This should work even if there are spaces in the file.
// The operator >> will drop leading white space
// Then read the next type
// For int object will read an integer from the stream
// For char object will read the next char (after dropping leading white space)
linestream >> a >> sep >> b >> sep >> c >> sep >> d;
How do we get these four values into a matrix-like data structure? First, declare this somewhere with appropriate scope & lifetime:
std::vector< std::vector<int> > matrix; // to hold everything.
Next, add this code to your line-reading loop:
{
std::vector <int> vi;
vi.push_back(a);
vi.push_back(b);
vi.push_back(c);
vi.push_back(d);
matrix.push_back(vi);
}
Finally, in your code that analyzes the matrix:
int item;
item = matrix[0][0] + matrix[1][1] + matrix[2][2]; // for example.
精彩评论