My input .txt looks as follows:
6 3
0 1 5
0 2 1
0 5 53
From the second line onwards I want to store the columns in arrays, so I did the following:
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;
}
My output is the following:
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
Does anyone know where these numbers come from? I'm new to C++ and appreciate any hints about what goes wrong here.
I am not sure how this code already compiled but: Issue One:
cout<<"first array"<<Array1<<endl;
cout<<"second array"<< Array2<<endl;
cout<<"third array"<< Array3<<endl;
I think this will display the hexadecimal address of each array, since you didn't type which element Array[?]
in every array you are tying to display.
Issue Two:
for(int i = 1; i < NumOne + 1; i++){
infile >> Array1[i-1] >> Array2[i-1] >> Array3[i-1];
This code will set junk data, since it's going to try reading NumOne + 1 means 6 + 1 = 7 lines as max while you only have 3 lines. So what are you trying to do here?
Issue Three:
you need to set a fixed size before declaring any array. So int Numone = ?
or Array[?]
Try this part of using vectors if you need to set the size of your container during run time
#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;
}