David Li
David Li

Reputation: 125

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?

Upvotes: 0

Views: 1671

Answers (1)

Thomas Matthews
Thomas Matthews

Reputation: 57749

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.

Upvotes: 1

Related Questions