How to read data from file c++

I have a data.txt file organizing as follows:


nodeNum 10 NodeId Coordinates 0 0 0 1 1 1 2 2 2 3 3 3 4 4 4 5 5 5 6 6 6 7 7 7 8 8 8 9 9 9 Edge(from i to j) Weight 0 1 1.5 1 1 2.1 2 1 3.3 3 1 4.0 4 1 5.0 5 1 6.6 6 1 3.7 7 1 8.1 8 1 9.3 9 1 10.2


How can I read and store the data in as follows:

int nodeNumber; // <--------- get and store number in line number 2 in text file.

std::vector<Node> nodes(nodeNumber);   
double x1, y1;

for (int i=0; i< nodeNumber; i++) {
    nodes.at(i) = g.addNode();
    x1 , y1 //<-- x1 and y1 store coordinate from line 4 to line 4 + nodeNum, respectively 
    coord[nodes.at(i)].x=x1;
    coord[nodes.at(i)].y=y1;
} 

From the line:

Edge(from i to j) Weight //(line number 3+nodeNum (=3+10) ) to the end. i <-- first number, j <-- second number, z[i,j] < --- 3th number.

I have no idea to do this. Can anyone please help me?

Answers


I recommend using class or struct to represent a line of data from the file. Next would be to overload operator>> to read in the data (and optionally removing the newline).

struct Coordinate
{
  int x, y, z;
  friend istream& operator>>(istream& input, Coordinate& c);
};

istream& operator>>(istream& input, Coordinate& c)
{
  input >> x >> y >> z;
  return input;
}

You input loop for a vector of coordinates becomes:

std::vector<Coordinate> points;
Coordinate c;
while (data_file >> c)
{
  points.push_back(c);
}

The input will fail when reading something that is not a coordinate. At this point, clear the stream state and read the edge records.


Need Your Help

Create a record for each column AND each row SSIS

database csv ssis pivot ssis-2008

I'm builiding a SSIS-package that will update/create records in a database based on survey answers.

How to find the size of iphone camera photo and how can I resize it?

ios objective-c iphone

I took camera photo and a library photo on my app and I have to send it on the server. So I want to know which is the size of the photo and I want to restrict the number of it's pixels. Can anybody...