How to convert int to QString? - c++

Is there a QString function which takes an int and outputs it as a QString?

Use QString::number():
int i = 42;
QString s = QString::number(i);

And if you want to put it into string within some text context, forget about + operator.
Simply do:
// Qt 5 + C++11
auto i = 13;
auto printable = QStringLiteral("My magic number is %1. That's all!").arg(i);
// Qt 5
int i = 13;
QString printable = QStringLiteral("My magic number is %1. That's all!").arg(i);
// Qt 4
int i = 13;
QString printable = QString::fromLatin1("My magic number is %1. That's all!").arg(i);

Moreover to convert whatever you want, you can use QVariant.
For an int to a QString you get:
QVariant(3).toString();
A float to a string or a string to a float:
QVariant(3.2).toString();
QVariant("5.2").toFloat();

Yet another option is to use QTextStream and the << operator in much the same way as you would use cout in C++:
QPoint point(5,1);
QString str;
QTextStream(&str) << "Mouse click: (" << point.x() << ", " << point.y() << ").";
// OUTPUT:
// Mouse click: (5, 1).
Because operator <<() has been overloaded, you can use it for multiple types, not just int. QString::arg() is overloaded, for example arg(int a1, int a2), but there is no arg(int a1, QString a2), so using QTextStream() and operator << is convenient when formatting longer strings with mixed types.
Caution: You might be tempted to use the sprintf() facility to mimic C style printf() statements, but it is recommended to use QTextStream or arg() because they support Unicode strings.

I always use QString::setNum().
int i = 10;
double d = 10.75;
QString str;
str.setNum(i);
str.setNum(d);
setNum() is overloaded in many ways. See QString class reference.

A more advanced way other than the answer of Georg Fritzsche:
QString QString::arg ( int a, int fieldWidth = 0, int base = 10, const QChar & fillChar = QLatin1Char( ' ' ) ) const
Get the documentation and an example here.

If you need locale-aware number formatting, use QLocale::toString instead.

Just for completeness, you can use the standard library and do:
QString qstr = QString::fromStdString(std::to_string(42));

QLocale has a handy way of converting numbers.  It's not much more typing than the accepted answer, but is more useful in the case of floats; so I like to do both this way.  Here's for an int:
int i = 42;
QString s = QLocale().toString(i);
and here's for a float:
float f=42.5;
QString s = QLocale().toString(f, 1);
the last argument is the number of decimal places.  You can also insert a char format argument such as 'f' or 'e' for the second parameter. The advantage of this, is if your program is then run in a locale where a comma is used as a decimal "point", it will automatically print it that way.  It's not included in something like <QCoreApplication>, so you'll have to do an #include <QLocale> somewhere, of course.  It really comes into its own in formatting currency strings.
It has the slight performance downside of requiring the creation and deletion of an object during the evaluation, but were performance an issue, you could just allocate it once, and use it repeatedly.
You could write:
QString s = QString::number(42.5, 'f', 1);
but according to the help "Unlike QLocale::toString(), this function does not honor the user's locale settings."

Related

What is the most appropriate way to concatenate with MFC's CString

I am somewhat new to C++ and my background is in Java. I am working on a hdc printing method.
I would like to know the best practice for concatenating a combination of strings and ints into one CString. I am using MFC's CString.
int i = //the current page
int maxPage = //the calculated number of pages to print
CString pages = ("Page ") + _T(i) + (" of ") + _T(maxPage);
I would like it to look like 'Page 1 of 2'. My current code does not work. I am getting the error:
Expression must have integral or enum type
I have found more difficult ways to do what I need, but I want to know if there is a simple way similar to what I am trying. Thanks!
If that's MFC's CString class, then you probably want Format which is a sprintf-alike for it:
CString pages;
pages.Format(_T("Page %d of %d"), i, maxPage);
i.e. you can assemble the string using regular printf-format specifiers substituting in the numbers at runtime.
You can use also stringstream classes
#include <sstream>
#include <string>
int main ()
{
std::ostringstream textFormatted;
textFormatted << "Page " << i << " of " << maxPage;
// To convert it to a string
std::string s = textFormatted.str();
return 0;
}
std::string has all you need:
auto str = "Page " + std::to_string(i) + " of " + std::to_string(maxPage);
As stated correctly in the comment, you can access the underlying C-string via str.c_str(). Here is a live working example.
If you have C++11 you can use std::to_string: std::string pages = std::string("Page ") + std::to_string(i) + (" of ") + std::to_string(maxPage);
If you don't have C++11 you can use an ostringstream or boost::lexical_cast.

How to print string literal and QString with qDebug?

Is there any easy way to get the following work? I mean is there any helper class in Qt which prepares the string for qDebug?
QString s = "value";
qDebug("abc" + s + "def");
You can use the following:
qDebug().nospace() << "abc" << qPrintable(s) << "def";
The nospace() is to avoid printing out spaces after every argument (which is default for qDebug()).
No really easy way I am aware of. You can do:
QByteArray s = "value";
qDebug("abc" + s + "def");
or
QString s = "value";
qDebug("abc" + s.toLatin1() + "def");
According to Qt Core 5.6 documentation you should use qUtf8Printable() from <QtGlobal> header to print QString with qDebug.
You should do as follows:
QString s = "some text";
qDebug("%s", qUtf8Printable(s));
or shorter:
QString s = "some text";
qDebug(qUtf8Printable(s));
See:
http://doc.qt.io/qt-5/qtglobal.html#qPrintable
http://doc.qt.io/qt-5/qtglobal.html#qUtf8Printable
Option 1: Use qDebug's default mode of a C-string format and variable argument list (like printf):
qDebug("abc%sdef", s.toLatin1().constData());
Option 2: Use the C++ version with overloaded << operator:
#include <QtDebug>
qDebug().nospace() << "abc" << qPrintable(s) << "def";
Reference: https://qt-project.org/doc/qt-5-snapshot/qtglobal.html#qDebug
Just rewrite your code like this:
QString s = "value";
qDebug() << "abc" << s << "def";
I know this question is a bit old, but it appears nearly on top when searching for it in the web. One can overload the operator for qDebug (more specific for QDebug) to make it accept std::strings like this:
inline QDebug operator<<(QDebug dbg, const std::string& str)
{
dbg.nospace() << QString::fromStdString(str);
return dbg.space();
}
This thing is for years in all of my projects, I nearly forget it is still not there by default.
After that, usage of << for qDebug() is a lot more usable imho. You can even mix QString and std::string. Some additional(but not really intended) feature is, that you sometimes can throw in integers or other types that allow implicit conversion to std::string .

C++, best way to change a string at a particular index

I want to change a C++ string at a particular index like this:
string s = "abc";
s[1] = 'a';
Is the following code valid? Is this an acceptable way to do this?
I didn't find any reference which says it is valid:
http://www.cplusplus.com/reference/string/string/
Which says that through "overloaded [] operator in string" we can perform the write operation.
Assigning a character to an std::string at an index will produce the correct result, for example:
#include <iostream>
int main() {
std::string s = "abc";
s[1] = 'a';
std::cout << s;
}
For those of you below doubting my IDE/library setup, see jdoodle demo: http://jdoodle.com/ia/ljR, and screenshot: https://imgur.com/f21rA5R
Which prints aac. The drawback is you risk accidentally writing to un-assigned memory if string s is blankstring or you write too far. C++ will gladly write off the end of the string, and that causes undefined behavior.
A safer way to do this would be to use string::replace: http://cplusplus.com/reference/string/string/replace
For example
#include <iostream>
int main() {
std::string s = "What kind of king do you think you'll be?";
std::string s2 = "A good king?";
// pos len str_repl
s.replace(40, 1, s2);
std::cout << s;
//prints: What kind of king do you think you'll beA good king?
}
The replace function takes the string s, and at position 40, replaced one character, a questionmark, with the string s2. If the string is blank or you assign something out of bounds, then there's no undefined behavior.
Yes. The website you link has a page about it. You can also use at function, which performs bounds checking.
http://www.cplusplus.com/reference/string/string/operator%5B%5D/
Yes the code you have written is valid. You can also try:
string num;
cin>>num;
num.at(1)='a';
cout<<num;
**Input**:asdf
**Output**:aadf
the std::replace can also be used to replace the charecter. Here is the reference link http://www.cplusplus.com/reference/string/string/replace/
Hope this helps.
You could use substring to achieve this
string s = "abc";
string new_s = s.substr(0,1) + "a" + s.substr(2);
cout << new_s;
//you can now use new_s as the variable to use with "aac"

QString::number() 'f' format without trailing zeros

I want to convert number to QString with 3 significant digits.
QString::number(myNumber,'f',3);
does the job but remains trailing zeros. How to use it without them.
Also I've tried 'g' and which shouldn't remain those zeros:
QString::number(myNumber,'g',3);
but for example 472.76 is converted to 473. That surprised me. Why is it so with 'g' option?
However I am interested in 'f' format. So the main question is how to do it with 'f' without trailing zeros?
Input -> Desired output
472.76 -> 472.76
0.0766861 -> 0.077
180.00001 -> 180
I'm almost embarrassed to post this but it works:
QString toString( qreal num )
{
QString str = QString::number( num, 'f', 3 );
str.remove( QRegExp("0+$") ); // Remove any number of trailing 0's
str.remove( QRegExp("\\.$") ); // If the last character is just a '.' then remove it
return str;
}
If you're really concerned about the performance using this method you may want to come up with a different solution.
QString::number(myNumber,'g',3);
Will limit the conversion to the significant digits. You'll most always have 3 numbers.
472.76 => 472
4.7276 => 4.72
Try using the formatted printing functions like QString::sprintf. This should give you more control.
QString numStr;
numStr.sprintf("f.3f", myNumber);
If you insist to have the precision after the decimal point you have to use 'f'. Here is an option to remove the trailing zeors with better performance than the Regex using only QString builtins:
QString str = QString::number(myNumber,'f',3);
while(str.back() =='0')
{
str.chop(1);
}
if(str.back() =='.')
{
str.chop(1);
}
This works because the f option guarantees to put out the defined digits.
It's about 50% faster than C sprintf and 40% faster than QString::sprintf from the other answer.
QString str;
str.setNum(myNumber, 'f', 3);
This will do what you need, I tested it. Strangely, "number" behaves differently than "setNum".
How about this. It is maybe more performant than the variant with regular expressions.
The mynumber() function takes a new format char 'h', which does the job.
QString mynumber(qreal p_number, char p_format, int p_precision)
{
if(p_format=='h')
{
//like 'f' but removes trailing zeros and the '.' evtl
QString res=QString::number(p_number,'f',p_precision);
int countTrailingToRemove=0;
for(QString::const_reverse_iterator it=res.crbegin();it!=res.crend();it++)
{
if(*it=='0') countTrailingToRemove++;
else
{
if(*it=='.') countTrailingToRemove++;
break;
}
}
return res.mid(0,res.length()-countTrailingToRemove);
}
return QString::number(p_number,p_format,p_precision);
}

How do I insert a variable result into a string in C++

I just started learning C++ in Qt and I was wondering how can I put a variables result in a string? I'm trying to use this for a simple application where someone puts their name in a text field then presses a button and it displays there name in a sentence. I know in objective-c it would be like,
NSString *name = [NSString stringWithFormatting:#"Hello, %#", [nameField stringValue]];
[nameField setStringValue:name];
How would I go about doing something like this with C++? Thanks for the help
I assume we're talking about Qt's QString class here. In this case, you can use the arg method:
int i; // current file's number
long total; // number of files to process
QString fileName; // current file's name
QString status = QString("Processing file %1 of %2: %3")
.arg(i).arg(total).arg(fileName);
See the QString documentation for more details about the many overloads of the arg method.
You don´t mention what type your string is. If you are using the standard library then it would be something along the lines of
std::string name = "Hello, " + nameField;
That works for concatenating strings, if you want to insert other complex types you can use a stringstream like this:
std::ostringstream stream;
stream << "Hello, " << nameField;
stream << ", here is an int " << 7;
std::string text = stream.str();
Qt probably has its own string types, which should work in a similar fashion.
I would use a stringstream but I'm not 100% sure how that fits into your NSString case...
stringstream ss (stringstream::in);
ss << "hello my name is " << nameField;
I think QString has some nifty helpers that might do the same thing...
QString hello("hello ");
QString message = hello % nameField;
You could use QString::sprintf. I haven't found a good example of it's use yet, though. (If someone else finds one, feel free to edit it in to this answer).
You might be interested in seeing information about the difference between QString::sprintf and QString::arg.