[英]How to read data from file c++
我有一個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;
}
從該行:
邊緣(從i到j)權重//(行號3 + nodeNum(= 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);
}
讀取不是坐標的內容時,輸入將失敗。 此時,清除流狀態並讀取邊緣記錄。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.