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

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

本文关键字:存储 向量 数据 C++ 中将 txt      更新时间:2023-10-16

我的输入.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;
    }