[英]Store a .txt file columns into an array in c++
我是編程新手,所以我有一個基本問題。 我目前有一個包含2列的文本文件。 每行有x和y數字,用空格分隔。 這些是文件的前五行:
120 466
150 151
164 15
654 515
166 15
我想讀取數據並將它們存儲到x和Y列中,然后在程序中的其他地方調用數據,例如x [i]和y [i]。 說,我不知道行數。 這是我的代碼的一部分,我試圖這樣做。
#include <fstream>
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
double X[];
double Y[];
ifstream inputFile("input.txt");
string line;
while (getline(inputFile, line))
{
istringstream ss(line);
double x,y;
ss >> x >> y;
X = X + [x];
Y = Y + [y];
return 0;
}
}
好的事情是使用矢量:
vector<double> vecX, vecY;
double x, y;
ifstream inputFile("input.txt");
while (inputFile >> x >> y)
{
vecX.push_back(x);
vecY.push_back(y);
}
for(int i(0); i < vecX.size(); i++)
cout << vecX[i] << ", " << vecY[i] << endl;
推薦的方法是使用std::vector<double>
或兩個(每列一個),因為可以很容易地將值添加到它們中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.