Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

qt

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

like image 946
Natatos Avatar asked Sep 25 '11 01:09

Natatos


3 Answers

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.

like image 106
Ken Bloom Avatar answered Nov 19 '22 17:11

Ken Bloom


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.

like image 32
K-ballo Avatar answered Nov 19 '22 16:11

K-ballo


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;
like image 1
Andrew White Avatar answered Nov 19 '22 17:11

Andrew White