PDA

View Full Version : Append inserting random char into beginning of QTString



TomJoad
22nd March 2011, 17:27
Hello everyone, I'm making a small program that will ease the process of opening files at the law firm I work for. Anyways, I'm having a difficult time with the append class of QTString.

I am trying to write to a csv file through user input, but need to get past this step first. (everything but 1 will be through user input, and date will take the system date)

The specific format it needs to look like is:
,"defendant",advs.,"plaintiff",Lawyer,1,date,,,,,,

The function:

void csvWriting()
{
QFile file("register.csv");
file.open(QIODevice::Append | QIODevice::Text);
QDataStream out(&file);
QString string = " ,";
QString defendant = "Defendant";
QString camma = ",";
QString advs = "advs.";
QString plaintiff = "Plaintiff";
QString lawyer = "lawyer";
QString date = "date";
QString ending = ", , , , , \n";
string.append(defendant + camma + advs + camma + plaintiff + camma + lawyer + camma + date + ending);
out << string;
file.close();
}

However, when it outputs, a random character (seems to like b/d) is inserted into the string:


d , D e f e n d a n t , a d v s . , P l a i n t i f f , l a w y e r , d a t e , , , , ,


I'm assuming it has something to do with the appending process as when I was doing the test writing with a single string this did not happen. Does a "," have an escape character I could use instead? The subsequent "," that are appending don't produce this outcome though...

Where is this d coming from, and how would I fix it? As a side note, I am not sure why all the letters have spaces between them, but, for my purposes, it doesn't seem to matter.

(perhaps it would just be easier to do "out << string; out << camma;" etc.)

high_flyer
22nd March 2011, 17:39
The problem (probably) has to do with you using QDataStream.
Use QTextStream.
Also you can do all this much more elegant if you append strings to a QStringList, and then loop for adding the commas when you output to the file.
Like so:


QStringList strList;
strList<<"some string";
strList<<"some other string";
...
QFile file;
//open file etc
QTextStream out(&file);
for(int i=0; i<strList.size()-1; i++){
out<<strList<<",";
}
out<<strList.at(strList.size()-1); //to avoid comma after the last string.

TomJoad
22nd March 2011, 18:08
Using QTextStream actually fixed all of the problems. I will investigate QStringList later tonight as it looks very useful.

It's taken me a while to wrap my head around C++ and QT and it finally feels like it is starting to come together.

Thank you.

ChrisW67
23rd March 2011, 00:16
Or just:


QStringList parts;
parts << "1" << "2" << "3";
...
out << parts.join(",");

Depending on what will read the file, you might also need to account for the possibility of commas or quotes in some of the parts.