3

This is what I'm trying to do:

showMessage("ERROR: THE MAX IS:" + max);

Basically I want to concatenate a variable (in this case an int) with a string to pass it as a parameter.

How can I do this in C++?

0

4 Answers 4

5

Here's one way:

std::ostringstream msg;
msg << "ERROR: THE MAX IS: " << max;
showMessage(msg.str());
Sign up to request clarification or add additional context in comments.

Comments

3

Personally, if you're going that route for displaying something, no need to have the user do extra work:

#include <iostream>

template<typename T>
void showMessage(T &&t) {
    std::cout << t << "\n";
}

template<typename Head, typename... Tail> 
void showMessage(Head &&head, Tail&&... tail) {
    std::cout << head;
    showMessage(std::forward<Tail>(tail)...);
}

int main() {
    showMessage("value1: ", 5, " and value2: ", 'a');
}

Here's a live example. Any stream should work, including a string stream and file stream. Keep in mind this is very similar to just using a stream and only really worth it if you do other stuff along with displaying it.

Comments

1

A combination of std::string and std::to_string() gives a touch of C++11 goodness:

#include <iostream>
#include <string>

using namespace std;


int main() {
    int max = 42;
    std::string mess("ERROR: THE MAX IS: ");
    mess += std::to_string(max);
    std::cout << mess;
}

LIVE EXAMPLE

If you want to use the string as an argument to a function accepting a const char*, you can use std::string::c_str() to get the C-style string of the std::string:

func(mess.c_str());

Comments

1

There isn't a stock C++ way to do this, string literals are that, and they're generally constant. You'll either need to use an overloaded string class or you'll need to make showMessage take arguments and do some kind of formatting for you.

// simple version - take a single string.
void showMessage(const std::string& message) {
    // your old code, e.g. MessageBoxA(NULL, message.c_str(), "Message", MB_OK);
}

// complex version, take lots of strings.
void showMessage(std::initializer_list<std::string> args) {
    std::string message = "";
    for (auto str : args)
       message += str;
    showMessage(message);
}

int main(int argc, const char* argv[]) {
    showMessage("Simple version");
    showMessage({ "This program is: ", argv[0], ". Argument count is: ", std::to_string(argc) });
    return 0;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.