如何从文件 c++ 读取数据

How to read data from file c++

本文关键字:读取 数据 c++ 文件      更新时间:2023-10-16

我有一个data.txt文件,组织如下:


节点数
10
节点 ID 坐标
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
边缘(从 i 到 j) 重量

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


如何读取和存储数据,如下所示:

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;
} 

从行:

边(从 i 到 j) 权重//(行号 3+节点数 (=3+10) ) 到最后。
i <-- 第一个数字, j <-- 第二个数字, z[i,j] <---第三个数字。

我不知道这样做。谁能帮我?

我建议使用classstruct来表示文件中的一行数据。 接下来是重载operator>>读取数据(并选择性地删除换行符)。

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;
}

坐标向量的输入循环变为:

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

读取非坐标的内容时,输入将失败。 此时,清除流状态并读取边缘记录。