在 C++ 中将.txt中的数据存储为列向量
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;
}
相关文章:
- 访问存储在向量C++中的结构的多态成员
- 添加存储在向量中的大整数的函数出现问题
- 在 std::无符号字符的向量处存储 int 的十六进制表示形式
- 如何从用户那里获取输入并将其存储在向量中?
- 如何从文件中读取两个字符串和数字数组,并将它们存储在对象向量中
- 将无符号字符的向量存储在数组中会给我 std::bad_alloc
- 在二维向量或数组中可以存储的最大元素数是多少?
- 存储在堆分配向量中的指针的免费存储
- 将相同共享指针的副本存储在不同的向量中是否是一种好的做法?
- 将数组信息存储到 c++ 向量中有一个"Access violation reading location"
- Sqlite3:将数据库表名存储在向量中
- 如何在数组和向量 c++ 中存储和保存输入
- C++ 将抽象类型的动态分配对象传递给函数并存储在向量中
- 是否可以在类中存储unique_ptr,并在C++中存储向量?
- 在向量 C++14(无限制联合)的结构内的联合中创建和存储字符串
- 在固定大小的向量中存储指向元素的指针
- 无法将派生类存储在基类指针的向量中
- 如何访问和存储向量类型的结构成员
- 如何按索引存储向量的向量
- findnonzero() 中存储向量<Point>中非零元素的坐标时出错