I'm having a problem filling a vector from a file. Basically, it is adding an empty element at the end. I'm new to Qt and haven't worked with file streams much so I could use a suggestion on how to stop the stream before it adds the extra element.
void gui::get_data()
{
mileage.clear();
QFile file(file_label->text() + ".txt");
QTextStream in(& file);
float m;
float g;
QString d;
if(!file.open(QFile::ReadOnly))
{
// Send failure to status bar
ui->statusBar->showMessage("File failed to open");
return;
}
while(true)
{
if(in.atEnd())
{
break;
}
else
{
in >> m >> g >> d;
mileage.push_back(Entry(m, g, d));
}
}
file.close();
But, if I add another element to the vector and write that the file look like this.
//file after adding element
132654 0 02132014
132654 0 02132014
0 0
132998 22 02202014
I have it set to append at the moment so that is why the first line is repeated. I figure the problem is with if(in.atEnd()). I could fix it by deleting the last element right after adding it, but that seems like more of a hack than anything else.
Just a wild guess, as I am not familiar with the QT API, but are you skipping the newline sequence after each record properly? Seems that atEnd would return false one too many times if you have a newline after your last record. *Refer to the QFile docs for the 'default' return values for the extraction operator specializations to confirm. My guess would be that the specializations for numerical types would return '0' and an empty string upon eof.
Good guess, I think that is exactly the problem. The empty string is there, but you obviously can't see it until a second addition and write is performed and it gets really weird. I was looking in QTextStream for a solution, but I'll check QFile.
This might or might not be related, but I found "\n" didn't work as I expect it to writing to file and ended up using "\r\n" to start a new line.
Hmmm, I couldn't find another way around it except to use readLine() which I didn't use in the first place because as far as I can tell reads the line as one string. In order to split the string I would need to use a QStringList and them write that to the vector. The best I could come up with was to add another if like this.