Reputation: 33956
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++?
Upvotes: 3
Views: 8115
Reputation: 24249
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;
}
Upvotes: 1
Reputation: 61910
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.
Upvotes: 3
Reputation: 17708
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;
}
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());
Upvotes: 1
Reputation: 64308
Here's one way:
std::ostringstream msg;
msg << "ERROR: THE MAX IS: " << max;
showMessage(msg.str());
Upvotes: 5