Snprintf usage?
-
Trying to use snprintf but -QT- Qt isn't recognizing the function. I've included <stdio.h> but I'm using namespace std; due to using vectors. Any help here would be appreciated, thanks.
-
Hi,
snprintf is not a function of Qt, and also not of the STL (namespace std).
Which platform and which compiler tool chain are you using?I found this page, which describes that there are versions of printf in std namespace (include cstdio) but I've never seen that before.
-
[quote author="Lukas Geyer" date="1331209027"]There is qsnprintf(), a portable version of snprintf(); the "correct" way of doing such things however is using QString::sprintf().[/quote]
Hm... According to this site:
http://qt-project.org/doc/qt-4.8/qstring.html#sprintf
"Warning: We do not recommend using QString::sprintf() in new Qt code."snprintf is a buffer_overrun_safe function, this is relatively new thing in the C/C++ world, so it can be used only under the newest C and C++ compilers.
-
Actually, I've found very little use to use any of the printf-related functions in Qt, as there are native QString methods for formatting and manipulating string contents appropriately. Depending on what you'd like to use snprintf() for, there is most likely a native Qt solution available through QString that would be more appropriate.
-
Thanks for the help. Can't say I've solved my problem, but to do that I'll be posting a new thread in the Qt Dev forum as the issue is related to the pixmap's loadFromData method.
-
It would be:
#include <cstdio>
...
char buf[4];
std::snprintf(buf, 4, "foo");
qDebug() << QString(buf);
or you can use qsnprintf();.
If you want Unicode, you have to use STL:
wchar_t buf[4];
std::swprintf(buf, 4, L"foo");
qDebug() << QString().fromWCharArray(buf);
-
@Morbius said in Snprintf usage?:
If you want Unicode, you have to use STL:
wchar_t buf[4];
std::swprintf(buf, 4, L"foo");
qDebug() << QString().fromWCharArray(buf);No, you don't. You can simply do
qDebug() << QStringLiteral(u"foo");
, and please don't usewchar_t
if you don't have to. It's not portable and annoying. There are modern replacements likechar16_t
.