Natatos
Natatos

Reputation: 145

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

Upvotes: 10

Views: 55081

Answers (4)

Ken Bloom
Ken Bloom

Reputation: 58790

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.

Upvotes: 9

Ken Bloom
Ken Bloom

Reputation: 58790

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.

Upvotes: 0

K-ballo
K-ballo

Reputation: 81379

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.

Upvotes: 9

Andrew White
Andrew White

Reputation: 53516

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;

Upvotes: 1

Related Questions