Input .txt matrix into 2d array without asking for rows and columns

Sep 22, 2012 at 7:01am
Hey guys,
I've run into a problem where I need to input a matrix into a 2d array from a text file without asking for the rows and columns.

when opening the text file, it'll usually look something like this...
For example a 4x3 matrix.

1 2 0
855 0 4
5 6 0
0 100 88

I can input these numbers successfully using this code if I know the rows and columns.

int rows, columns;
float matrix1[10][10];
ifstream textfile;
textfile.open("numbers.txt");
for(int i=0; i<rows; i++)
{
for(int j=0; j<columns; i++)
{
textfile >> matrix1[i][j];
}
}

I read elsewhere that I could possibly get the number of rows and columns if I figure out how many elements are in the file, but I just don't see how.

Does anyone have previous experience doing this?

Thanks,
Jacob
Sep 22, 2012 at 7:27am
One way or another you'll end up parsing the file line by line.
Look up the ifstream member getline(). The idea is to take 1 line at a time and then read each group of non-whitespace characters into the array. Since you don't know the size of the matrix/file you can loop it like this:

1
2
3
4
5
6
7
textfile.open("numbers.txt");
while(textfile)
{
   //getline() here
  //then 'for' loop until the parse reaches the end of the columns
  //then move the row index then 'continue' the while loop
}


Instead of getline(), the other option is to use textfile >> matrix1[i][j]; like you are except that you'll have to keep checking for the newline character to know when to start a new row. getline() does this automatically for u...
Last edited on Sep 22, 2012 at 7:29am
Sep 24, 2012 at 8:02pm
Hey, thanks for the reply.
I looked into getline and decided I'm going to use that.

So far I've developed this code... but I have one question about it. Does C++ support a function called "hasmoretokens()" used in the string tokenizer class? It existed in java which was the language I used in my fundamentals 2 class.

string array1[10];
string temp;
int rows=0; int columns=0;

getline(textfile, temp)
while(temp.hasmoretokens())
{
array1[i] = temp.next();
columns++;
i++
}

I made a 1d array in order to just get the number of columns; I'm going to delete that memory afterwards.

then to get number of rows:

while(!textfile.eof())
{
getline(textfile, temp);
rows++;
}

Then I would just use my code from the first post to enter the numbers from the textfile to a 2d array of strings then convert to floats.
Sep 24, 2012 at 10:29pm
Alright I guess c++ doesn't really have anything called stringtokenizer, but stringstream seems to be the same thing, I'm going to mess around with that.
Sep 25, 2012 at 2:51am
I'm not sure about Java but you are correct that stringstream is probably what you're looking for and it's easy enough to implement.
Topic archived. No new replies allowed.