如何从文件 c++ 读取数据
How to read data from file c++
我有一个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] <---第三个数字。
我不知道这样做。谁能帮我?
我建议使用class
或struct
来表示文件中的一行数据。 接下来是重载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);
}
读取非坐标的内容时,输入将失败。 此时,清除流状态并读取边缘记录。
相关文章:
- 如何在ros2中从rosbag2读取数据
- OpenCV 和从 OutputArrays 或 (Mat) 读取数据
- 使用C++从磁卡读卡器MT188读取数据
- HDF5 简单读取数据集失败
- 嵌套结构,从由空行分隔的文件中读取数据
- 不要从输入队列套接字读取数据
- 从文件中读取数据,操作员>>
- 如何从excel文件中读取数据并存储到变量中?
- C++:从文件中读取x y数据会产生无限循环吗
- 无法通过FT232RL读取数据
- 如何从QNetworkReply读取数据?
- C++ 逐行从文件(包含空格)读取数据
- 通过显示一行星号来创建条形图,该条形图将读取数据的输入文件
- 我们可以从 TXT 文件中读取数据并使用 C 和 C++ 将其保存到 SQL 数据库吗?
- 从多个 tcp 连接读取数据
- 从文本文件中读取数据并删除所有换行符空格,并在 C++ 控制台中显示
- Qt TCP服务器不从客户端读取数据
- 累积从 C++11 中的文件中读取数据的整数
- 从 txt 文件中读取数据的最简单方法
- 从 txt 文件中读取数据的 Getline