0

I'm a Objective-C dev and sometimes I have to deal with C/C++ code. I have a function written in C++, it logs an event with name, for example, Level_12_Pack_10. I want to create a dynamic C++ string like that, then I can change level and pack numbers. In Objective C, it's easy with some lines of code: [NSString stringwithformat] but in C++, it's a bit difficult for me. Could anyone help me do it?

1
  • What you want is easy enough. Show us what you have tried. Look up std::string in the stl. You might look for examples of ostream operator<< overloading. Commented Oct 29, 2013 at 3:13

2 Answers 2

1

I don't think C++ supports strings with built-in changeable variables like that. It would be too over-the-top to make a class to format the string like that. Probably the closest thing you can get is to use stringstreams:

#include <sstream>
string makeMyString(int level, int pack) {
  stringstream ss;
  ss << "Level_" << level << "_Pack_" << pack;
  return ss.str();
}

If you have a string that you need to read and change the values inside, a similar function could be used.

Sign up to request clarification or add additional context in comments.

Comments

1

With c++11, it is drop dead simple just use std::to_string(level) etc to concatenate strings.

int level = 10;
int pack = 40;

std::string stuff = "Level_" + std::to_string(level) + "_Pack_" + std::to_string(pack);
//stuff is now "Level_10_Pack_40"
std::cout << stuff;

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.