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

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;

Tags:

C++

Qt