PDA

View Full Version : Function returns a gibberish value



ayanda83
14th March 2014, 19:36
Hi everyone, I have the function below. the function is suppose to generate an account number and return it in form of a QString.
QString NewAccount::genAccountNum()
{
QString tempStr, accNum;

int num1 = rand()%100000 + 999999;
tempStr.append(static_cast<QString>(num1));
accNum.append("AB");
accNum.append(tempStr);

return accNum;
}


The function returns the substring "AB" followed by gibberish, something that looks like Chinese fonts. AM I DOING SOMETHING WRONG HERE?

sulliwk06
14th March 2014, 20:02
I would use:
tempStr.append(QString::number(num1));

ChrisW67
14th March 2014, 20:28
As sulliwk06 says the function you want is QString::number() or QString::arg(). There is no meaningful way to cast an int to QString, so when you forced the compiler to do it anyway what you ended up with was something that will sometimes give rubbish and sometimes crash your program.