【问题标题】:How to read data from file c++如何从文件c ++中读取数据
【发布时间】:2016-04-24 03:47:35
【问题描述】:

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


节点编号
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(from i to j) Weight //(line number 3+nodeNum (=3+10) ) 到末尾。
i

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

【问题讨论】:

  • 问题是问题的核心是重复的,但整个问题与此处发布的有关从文件中读取整数的其他问题略有不同。
  • @dsz 为什么在 C++ 中有流时建议使用 fopenscanf
  • 好的,我知道 fopen 和 scanf 是老式的,我刚刚意识到标签正在寻找流解决方案。应该坚持我的最后一点。
  • @dsz “我知道 fopen 和 scanf 是老式的,...” 不,它们不是 old school,这些只是从来都不是 C++ 学校的一员。

标签: c++ file-io iostream fstream


【解决方案1】:

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

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

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

【讨论】:

  • 是否可以修改为逐行读取文件,只提取数值?
  • 是的。查找std::getlinestd::istringstream。因此,您可以使用std::istringstream,而不是使用data_file。 C++ 很好用这种方式,因为istringstream 是从istream 派生的,所以不需要更改Coordinate 类。
  • 但这仅有助于处理一个单独的路径。如何跳过第 1、3、14 行。如何读取第 2 行并存储在 int nodeNumber 和 STOP 中,然后声明一个大小为 nodeNumber 的向量?
  • 我的问题是我不知道如何读取第 2 行,将此数字存储到 int nodeNumber,然后停止。然后声明一个之前已经读过的nodeNumber大小的向量,继续从第4行到第14行读入number,存入ID,x[ID],y[ID]。从第 16 行到最后一行:读取 i
猜你喜欢
  • 2013-09-20
  • 1970-01-01
  • 2011-12-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多