My problems here is to take all the integers in a file, and store to an int array (of course without |
), and then do something with it (here I just need help to print out the array).
The data from the file is said to be a 10x10 matrix.
My code output is another 10x10 with trash values, as I tried using std::stringstream
.
Input:
1|11|2|13|2|2|2|11|13|2
1|11|2|13|2|2|2|13|2|11
1|13|1|13|2|2|2|2|2|2
1|13|1|12|2|2|2|2|2|2
1|13|1|13|1|2|2|2|2|2
1|13|1|13|1|1|2|2|2|2
1|13|1|13|1|1|1|2|2|2
1|13|1|13|1|1|1|1|2|2
1|13|1|13|1|1|1|1|1|2
1|13|1|13|1|1|1|1|1|1
Code:
#include<iostream>
#include<cstring>
#include<fstream>
#include<sstream>
using namespace std;
int main(){
//read data from file and store in a 2d array
ifstream myfile("input.txt");
string arr[10][20];
for(int i=0;i<10;i++){
for(int j=0;j<20;j++){
getline(myfile,arr[i][j],'|');
}
}
//convert string to int
//use stringstream
int arr2[10][20];
for(int i=0;i<10;i++){
for(int j=0;j<20;j++){
stringstream ss;
ss<<arr[i][j];
ss>>arr2[i][j];
}
}
//print arr2
for(int i=0;i<10;i++){
for(int j=0;j<20;j++){
cout<<arr2[i][j]<<" ";
}
cout<<endl;
}
myfile.close();
return 0;
}
The output should be:
1 11 2 13 2 2 2 11 13 2
1 11 2 13 2 2 2 13 2 11
1 13 1 13 2 2 2 2 2 2
1 13 1 12 2 2 2 2 2 2
1 13 1 13 1 2 2 2 2 2
1 13 1 13 1 1 2 2 2 2
1 13 1 13 1 1 1 2 2 2
1 13 1 13 1 1 1 1 2 2
1 13 1 13 1 1 1 1 1 2
1 13 1 13 1 1 1 1 1 1
My output:
1 11 2 13 2 2 2 11 13 2
1 13 2 2 2 2 2 2 13 1
1 2 2 2 2 2 13 1 13 1
1 2 2 2 13 1 13 1 1 1
1 2 13 1 13 1 1 1 1 1
1994842136 12 7086696 7085352 1994774642 0 1994842144 1994771436 0 0
6416848 2004213955 7086772 6416972 12 7086696 0 4 48 1994842112
2004213726 1 7149280 7149288 7086696 0 1988425164 0 2003400672 12
1999860416 6416972 2 1999966512 1999657456 1999691632 1999846272 1999845632 1999819744 1999860464
4194304 1994719472 0 6417024 0 6418312 2004471984 775517426 -2 6417120