Hi Guys, I am new to C++. I would really appreciate if you could help me with this problem...
Here is a sample text file. The first line contains two numbers which have to read first and they will determine how many rows and columns would be there in subsequent file. For eg: here we have 3 4 in the first line ( separated by space) and we have 3 rows and four columns after that. I want to read the first line to get to know how big array I should create to read the remaining lines. Then, rest of the file (except the last line) has be stored on another array ( containing 0 and 1). Finally, the last line has be read separately into a third array.
3 4
1 0 0 0
1 1 0 1
1 0 1 0
0 2 1 0 1 1
Here is what I have done so far. I don't think this is the most efficient way to do, but It works for the first two numbers. But after that it doesn't work. Please take a look and see if you can help:
# include <iostream>
# include <fstream>
# include <string>
usingnamespace std;
int main (){
char fName[20];
char buff1[8]; char buff2[8];
// Asking user for the file name and storing it
cout <<"Enter the file name" << endl;
cin >> fName ;
ifstream qFile(fName);
// Checking if the file is good
if (!qFile.good()){
cout << "Error reading the file"<< endl;
return 1;
}
// Reading the number of switches and light bulbs
qFile.getline(buff1,8,' ');
qFile.getline(buff2,8,' ');
// Printing out the first two numbers to confirm if the code is right.
for( int i = 0; i< 2; i++){
cout << buff1[i] ;
}
cout <<endl;
for( int i = 0; i< 2; i++){
cout << buff2[i] ;
}
cout <<endl;
// Converting the string to integet (to determine the size of the array)
int dim1 = atoi (buff1);
int dim2 = atoi (buff2);
// Reading the next set of lines into the second array
int* test;
test = newint [dim1*dim2];
for (int i = 0; i< dim2; i++)
{
for (int j = 0; j < dim1; j++)
{
qFile.getline(buff1,8,' ');
test[i*dim1+j] = atoi(buff1);
cout << test [i*dim1+j];
}
cout <<endl;
}
// Reading the last line until you find eol
qFile.close();
return 0;
}