I am working on a programing that needs to accept a text file as input and read that data into an NxM matrix. The only given size limitation is that the max row length is 1024. Additionally, the program needs to produce an error if all rows do not contain the same number of columns.
I figure that I need a 2D array to store the values, but I can't figure out how to do it, since I don't know the size to begin with.
int MAX_COLS=1024;
void readInput(ifstream & in)
{
int rows=1, cols=0;
float temp=0;
while (in.peek()!='\n')
//counts columns in first row
{
in>>temp;
cols++;
}
while (!in.eof())
{
int col_count=0;
if (in.peek()=='\n') //at the end of a line
{
in.ignore(3,'\n'); //ignore newline character
rows++;//increment rows
}
else
{
while (in.peek()!='\n')
//while not at end of line, count columns in current row
{
in>>temp;
col_count++;
if (in.eof())
break;
}
if (col_count!=cols) //if the columns in current row aren't equal to columns in first row, output Error and exit
{
cout<<"Error invalid data"<<endl;
exit(1);
}
}
}
cout<<"Rows "<<rows<<" Cols "<<cols<<endl;
in.close();
}
My code shows my function that computes rows and columns, and checks that each row has the same number of columns. In the code, I'm storing values in temp, but I need to change that to store them in a way that I can access them outside the loops.
Could someone please help me figure out a way to store these values?