繁体   English   中英

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

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM