Reading a matrix from a file

Hey everyone!

I should say first that I'm a complete beginner at C++ and this is the first project I have tried to create. I have done quite a bit of Matlab, but C++ is a lot harder! Anyway, I am very sorry if this is obvious but I've read all the manuals and as far as I understand, this should work.

I've built a matrixdouble class, whose constructor takes two arguments, the height of the matrix and its width. I want to read a file like this:

1 2 3
4 5 6 EOF

which will initialise a 2x3 matrixdouble object, based on the number of lines in the file (2 in this case) and the number of numbers in the first line. It will then populate the matrix's elements with the numbers, but I know how to do that. Right, so this is the code I'm struggling with:

#include "matrixdouble.hpp"
#include <stdlib.h>
#include <iostream>
#include <fstream>
#include <string>
#include <math.h>

using namespace std;

int main()
{
// get from user the name of the input file containing the matrix data
string fileName;
cout << "what is the name of your matrix file? ";
cin >> fileName;

// open the file
fstream matrixFile( fileName.c_str() );

// complain and close program if data file won't open
if (!matrixFile.is_open())
{
cout << "Can't open file \"" << fileName.c_str() << "\"" << endl;
return 0;
}

// count lines in file == rows in matrix
cout << "before while loop: " << matrixFile.tellg() << endl;
int size = 0;
string line;
while ( !matrixFile.eof() )
{
cout << "in loop...";
cout << matrixFile.tellg() << endl;
getline(matrixFile, line);
cout << line << endl << endl;
size++;
}

cout << "after while loop: " << matrixFile.tellg() << endl;


string line2;
matrixFile.seekg(0, ios::beg);

cout << "after seekg: " << matrixFile.tellg() << endl;

getline(matrixFile,line2);
cout << line2;
cout << "after a getline: " << matrixFile.tellg() << endl;

exit(0);
}

As you can see I've left messages in there to help to debug it, and if i use the file

'test.txt'
Hey baby
I want to know
will you be my girlEOF

as input, I get the following output:

what is the name of your matrix file? test.txt
before while loop: 0
in loop...9
Hey baby

in loop...24
I want to know

in loop...43
will you be my girl

after while loop: 43
after seekg: 0
after a getline: -1

In other words, the seekg call sends the cursor to the beginning of the file, but when I call getline, it doesn't assign the first line of the file to 'line2', and for some reason it decrements the get cursor to -1.

I guess I may be going about this the wrong way in the first place, any small bit of help or advice would be amazing as I have to hand in the project by tomorrow :-S

Many thanks,

Matt G.
Try to add matrixFile.clear() which sets the file stream state to good, after you reached the end of the file.
http://www.cplusplus.com/reference/iostream/ios/clear/
Topic archived. No new replies allowed.