[Solved] sprintf in qt
-
Hi,
I think that you should see on the Qt documentation for the api that create formatted strings. There are specific and complete functions / options for any kind of formatting reflecting the same options of sprintf.
-
QString::sprintf is not a static function. It alters the QString object. The correct way of using it is therefore:
@QString str;
// ...
str.sprintf("%s", tr_buff);@or
@QString str = QString().sprintf("%s", tr_buff);@
However if tr_buff is a QString already (which the error suggests), just use
@QString str = tr_buff;@ -
aditionally, sprintf is not a static member function.
@
QString wr_buff;
char* tr_buff = "XXX";
wr_buff.sprintf("%s",tr_buff);
@But you should take care:
bq. Warning: We do not recommend using QString::sprintf() in new Qt code. Instead, consider using QTextStream or arg(), both of which support Unicode strings seamlessly and are type-safe.
"see documentation of QString::sprintf":http://doc.qt.nokia.com/4.7/qstring.html#sprintf
If the requirement is to use sprint, are you sure, you shall do it with Qt? From my POV, it makes no sense, sorry...
EDIT: too slow..., Gerolf
-
[quote author="Gerolf" date="1316155835"]If the requirement is to use sprint, are you sure, you shall do it with Qt? From my POV, it makes no sense, sorry...[/quote]I've come across some cases where you might want to use sprintf (e.g. formatted double precision numbers: %3.8lf is not possible with QString::arg(), but sometimes desirable). The problem OP shows isn't one of them.
-
Btw, developing with Qt I think that the best practice is to use as possible the wide variety of api. At lest because grant one of the higher constan behavior on different platforms I have even see.
-
Very good. Ifthe problem is solved plese set your first post title with [Solved] in front. Thank you.
-
[quote author="Franzk" date="1316155969"]I've come across some cases where you might want to use sprintf (e.g. formatted double precision numbers: %3.8lf is not possible with QString::arg(), but sometimes desirable). The problem OP shows isn't one of them.
[/quote]This works for me:
@
double x = 42.23;
QString xStr = QString("%1").arg(x, 3, 'f', 8);
@Although the 3 in 3.8lf is superfluous, as the field width is 10 at least (the dot, eight digits after the dot and at least one digit before the dot).
-
@Volker: prfectly agree with you. In Qt there are a lot of possibilities so a downgrade using sprintf is to be avoided at all. I don't use it by the middle of years '90 :)