[英]Store a .txt file columns into an array in c++
I am new to programming, so I have what is probably a basic question. 我是编程新手,所以我有一个基本问题。 I currently have a text file with 2 columns.
我目前有一个包含2列的文本文件。 Each line has x and y numbers separated by white spaces.
每行有x和y数字,用空格分隔。 These are the first five lines of the file:
这些是文件的前五行:
120 466
150 151
164 15
654 515
166 15
I want to read the data and store them into x and Y columns and then call for the data some where else in the program for eg x[i] and y[i]. 我想读取数据并将它们存储到x和Y列中,然后在程序中的其他地方调用数据,例如x [i]和y [i]。 Say, I do not know the number of lines.
说,我不知道行数。 This is the part of my code where I attempt to do just that.
这是我的代码的一部分,我试图这样做。
#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;
}
}
the good thing to do is use vector: 好的事情是使用矢量:
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.