使用 C++ 从 .txt 文件读取数据并保存到多个向量中

Reading data from .txt file and saving into multiple vectors using c++

我有一个 data.txt 文件,其中包含如下数据:

1.0 0.5 1.5 0.01761
2.0 1.5 2.5 0.01977
3.0 2.5 3.5 0.02185

我正在尝试读取 data.txt 文件并将各个列中的数字存储到不同的向量中。例如,最左边一列的 1.0、2.0 和 3.0 将进入 vector<double> w,第二列的 0.5、1.5 和 2.5 将进入 vector<double> x。其余 2 列将分别进入 vector<double> yvector<double> z

我看过this and this等类似问题的其他回复。但是,它们没有解决将不同列的数据存储到不同向量中的问题。

以下是我目前的尝试:

#include <iostream>
#include <stdio.h>
#include <vector>

using namespace::std;

int main()
{
    FILE *f_read;
    double my_variable = 0;
    vector<double> w, x, y, z;
    f_read= fopen("data.txt", "r");

    for(int i = 0; i <= 3; ++i)
    {
        fscanf(f_read, "%.lf", &my_variable);
        w[i] = my_variable;
        fscanf(f_read, "%.lf", &my_variable);
        x[i] = my_variable;
        fscanf(f_read, "%.lf", &my_variable);
        y[i] = my_variable;
        fscanf(f_read, "%.lf", &my_variable);
        z[i] = my_variable;
    }

    //the following loop is printed to verify the vectors are correctly filled
    for(int j = 0; j <=3; ++j)
    {
        cout << "The " << j << "th value in w is " << w[j] << endl;
        cout << "The " << j << "th value in x is " << x[j] << endl; 
        cout << "The " << j << "th value in y is " << y[j] << endl;
        cout << "The " << j << "th value in z is " << z[j] << endl;
    }
return 0;
}

但是,最后一个 "for" 循环从未打印出来,程序返回 -1073741819。我的猜测是我在第一个循环中填充向量的方式有问题,但我看不出我的错误在哪里。

如有任何帮助,我将不胜感激。谢谢!

您正在访问 vector 的末尾,它们都是空的。正如您知道要处理的行数,您可以使用正确的大小初始化它们。

然后您可以直接读入 vector 的元素

#include <iostream>
#include <vector>

int main()
{
    std::vector<double> w(3), x(3), y(3), z(3);
    std::ifstream f_read("data.txt");

    for(int i = 0; i < 3; ++i)
    {
        f_read >> w[i] >> x[i] >> y[i] >> z[i];
    }
    return 0;
}

如果您不知道行数,则可以读入值和 push_back

    for(double w_, x_, y_, z_; f_read >> w_ >> x_ >> y_ >> z_; )
    {
        w.push_back(w_);
        x.push_back(x_);
        y.push_back(y_);
        z.push_back(z_);
    }