在c++中将.txt文件列存储到数组中

Store a .txt file columns into an array in c++

本文关键字:存储 数组 文件 c++ 中将 txt      更新时间:2023-10-16

我是一个编程新手,所以我有什么可能是一个基本的问题。我目前有一个文本文件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:

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>(每列一个),因为可以很容易地向它们添加值。