Hello,
EDIT: I know that QT users are only a very small subset of the forum-goers here, so in reading this post I think it's ok to consider the QT specific terms as compatible with regular C++ terms, i.e., a
QString
is essentially the same as a
std::string
. I have tried to identify these similarities in my post.
I'm trying to write a program in QT. In order to read in data from a file, something like this is typically done in the following way:
1 2 3 4 5 6 7 8 9 10
|
QString linecontents;
QString InputFile = "/home/file"; //QString is essentially a regular string
QFile InputFile_f(InputFile); //This is the file to be opened
InputFile_f->open(QIODevice::ReadOnly); //This opens the file
QTextStream InputStream(InputFile); //This creates a text stream for the opened file
while( !InputFile_f.atEnd() ) //.atEnd() is like <iostream>'s .eof()
{
linecontents = InputStream.readLine();
//Do other stuff...
}
|
Now, this is basically what I want to do. However, the issue is that creating a
QFile
object means that you must initialize it with the
QString
that is the file name (line 3 above). When my program is initialized, there is no file location because the user hasn't chosen which file he wants to open yet. Similarly, the
QTextStream
cannot be created yet because the
QFile
is incomplete (line 5 above).
My solution was to create initially just a pointer to a
QFile
object, and similarly a pointer to
QTextStream
. Then, whenever the user chooses the file they wish to open, I can create a
QFile
object and assign my pointer to that
QFile
, like so:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
|
class File
{
QString InputFile;
QFile* InputFile_f;
QTextStream* InputStream;
void OpenFile();
};
void File::OpenFile() //This function is called after user chooses file
{
QString linecontents;
InputFile_f = new QFile(InputFile);
InputFile_f->open(QIODevice::ReadOnly);
InputStream = new QTextStream(InputFile_f);
while( !InputFile_f.atEnd() )
{
linecontents = InputStream.readLine();
}
}
|
The problem is that the above function doesn't work; the
QTextStream
only reads the first line of my file and then stops, essentially indicating that it has reached the end of the file.
Now, in my mind everything I've done should work perfectly. However, months of programming have humbled me and I know that my logic must be incorrect. Can someone tell me what is wrong? I assume (and internet searches have hinted) that the problem lies with my pointers to
QFile
and
QTextStream
, and my usage of
new
.
I'm basically looking for someone to tell me why what I've done is incorrect, and also to recommend a change so that I can implement the program as I've described above.
Thanks!