Hello, I am happy to find this forum. I was trying to read a file to matrix matice.
The input file looks like this:
7 1 4 5 6 9
3 2 2 0 7 6
8 6 1 2 4 2
9 1 7 2 3 8
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(int argc, char *argv[]) {
string radka;
char * pch;
char * matice;
char * chradka;
int i=0;//cislo sloupce
int j=0;//cislo radky
int konecsouboru=0;
ifstream soubor("F:\\v\\prog\\vstup2.txt");
if (soubor.is_open())
{
konecsouboru=soubor.end;
cout<<konecsouboru<<endl;
matice = new char[konecsouboru+1,6];
while(!soubor.eof() )
{
getline(soubor,radka);
if(soubor.eof()) break;
chradka=new char[radka.size()+1];
strcpy(chradka,radka.c_str());
cout << radka << endl;//comment 1
i=0;
pch = strtok(chradka," ");
while (pch != NULL)
{
matice[i,j]=*pch;
cout<<matice[i,j];//comment 2
pch = strtok(NULL, " ");
i++;
}
cout<<endl;
cout<<matice[0,j]<<matice[1,j]<<matice[2,j]<<matice[3,j]<<matice[4,j]<<matice[5,j];//comment 3
cout<<endl;
j++;
delete[] chradka;
}
cout<<konecsouboru<<endl;
for(j=0; j<konecsouboru+1;j++)
{
for(i=0; i<6;i++)
{
cout<<"matice["<<i<<","<<j<<"]="<<matice[i,j];
}
if(j<konecsouboru)cout<<endl;
}
delete[] matice;
soubor.close();
}
else cout << "Soubor neslo otevrit.";
return 0;
}
With the input file at the beginning, the output looks like this:
2//should be a number of rows of the file minus 1
7 1 4 5 6 9//row read from file - comment 1
714569//row of the matrix parsed by strtok - comment 2
999999//the same matrix row after finishing loading the row by the //results of strtok function - comment 3
3 2 2 0 7 6
322076
666666
8 6 1 2 4 2
861242
222222
9 1 7 2 3 8
917238
888888
2//number of rows of the file again
//writing the matrix to screen to check how does it look like
matice[0,0]=9matice[1,0]=9matice[2,0]=9matice[3,0]=9matice[4,0]=9matice[5,0]=9
matice[0,1]=6matice[1,1]=6matice[2,1]=6matice[3,1]=6matice[4,1]=6matice[5,1]=6
matice[0,2]=2matice[1,2]=2matice[2,2]=2matice[3,2]=2matice[4,2]=2matice[5,2]=2
I can't find out why
1) I get 2 as a number of rows -1, when the input file has four rows
2) The matrix is not loaded by the values from file correctly
Could anybody please help me? I am trying to solve this problem for 3 days now:)
It should be a part of a much more complex algorithm and I am sad that I got stuck at this point.
Thank you very much for help.