将 .txt 中的数据存储为 C++ 中的列向量

storing data from .txt as column vectors in c++

我的输入 .txt 如下所示:

6 3
0 1 5
0 2 1
0 5 53

从第二行开始,我想将列存储在数组中,所以我做了以下操作:

main(int argc, char** argv)
{
    std::ifstream infile("instance1.txt");

    int NumOne, NumTwo;

    if (infile.good()){
        infile >> NumOne >> NumTwo;
    }

    int Array1[NumTwo];
    int Array2[NumTwo];
    int Array3[NumTwo];

    for(int i = 1; i < NumTwo + 1; i++){
        infile >> Array1[i-1] >> Array2[i-1] >> Array3[i-1];
    }

    infile.close();
    cout<<"first number"<<NumOne<<endl;
    cout<<"second number"<<NumTwo<<endl;

    for (int i=0; i < sizeof(Array1); i++){
        cout << Array1[i] << " " << Array2[i] << " " << Array3[i] << endl;
    }
    cout<<"first array"<<Array1<<endl;
    cout<<"second array"<< Array2<<endl;
    cout<<"third array"<< Array3<<endl;
}

我的输出如下:

first number6
second number5
0 1606413088 0
0 1 5
0 2 1
0 5 53
6923 5 1606414340
1 0 32767
1606673872 0 1606413088
32767 0 1
1606594089 0 2
32767 0 5
0 1 4
65793 2 5
80256 6923 5
0 1 0
80256 1606673872 0
0 32767 0
17623816 1606594089 0
1 32767 0
first array10x7fff5fbfeb10
second array20x7fff5fbfeaf0
third array0x7fff5fbfead0

有人知道这些数字是从哪里来的吗?我是 C++ 的新手,非常感谢有关这里出现问题的任何提示。

我不确定这段代码是如何编译的,但是: 问题一:

cout<<"first array"<<Array1<<endl;
cout<<"second array"<< Array2<<endl;
cout<<"third array"<< Array3<<endl;

我认为这将显示每个数组的十六进制地址,因为您没有键入要显示的每个数组中的哪个元素 Array[?]

问题二:

    for(int i = 1; i < NumOne + 1; i++){
    infile >> Array1[i-1] >> Array2[i-1] >> Array3[i-1];

此代码将设置垃圾数据,因为它将尝试读取 NumOne + 1 表示 6 + 1 = 7 行作为最大值,而您只有 3 行。那么你想在这里做什么?

问题三: 您需要在声明任何数组之前设置固定大小。所以 int Numone = ?Array[?]

如果您需要在 运行 时间

期间设置容器的大小,请尝试使用向量的这一部分
        #include <vectors>
        #include <iostream>
        int main(int argc, char** argv)
        {
            std::ifstream infile("instance1.txt");

        int NumOne, NumTwo;

        if (infile.good()){
            infile >> NumOne >> NumTwo;
        }

        std::vector<int> MyVectorOne(NumTwo);
        std::vector<int> MyVectorTwo(NumTwo);
        std::vector<int> MyVectorThree(NumTwo);

        for(int i = 1; i < NumTwo + 1; i++){ // again this is wrong. What do you want here??
            infile >> MyVectorOne[i-1] >> MyVectorOne[i-1] >> MyVectorOne[i-1];
        }

        infile.close();
        cout<<"first number"<<NumOne<<endl;
        cout<<"second number"<<NumTwo<<endl;

        for (int i=0; i < MyVectorOne.size(); i++){
            cout << MyVectorOne[i] << " " << MyVectorTwo[i] << " " << MyVectorThree[i] << endl;
        }

     // and here? what are you trying to display? this is also wrong
        cout<<"first array"<< MyVectorOne<<endl;
        cout<<"second array"<< MyVectorTwo<<endl;
        cout<<"third array"<< MyVectorThree<<endl;

        return 0;
    }