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

时间:2016-01-18 20:46:23

标签: c++ file-io iostream fstream

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

  

nodeNum
  10
  NodeId坐标
  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;
} 

从行:

  

Edge(从i到j)权重//(行号3 + nodeNum(= 3 + 10))到结尾。   
  i&lt; - 第一个数,j < - 第二个数,z [i,j]&lt; ---第3号。

我不知道这样做。有人可以帮帮我吗?

1 个答案:

答案 0 :(得分:1)

我建议使用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);
}

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

相关问题