0

In C# you were able to have a string, or other data, within a string. For example:

string myString = "Jake likes to eat {0}", food  

or

Console.WriteLine("Jake likes to eat {0}", food);

How can this be done in C++? For the program I am writing I have code that says:

getline(cin, obj_name);
property_names[j].Set_Type("vector<{0}>", obj_name);

How can I get the obj_name value to be placed within the braces?

zaerymoghaddam
  • 3,037
  • 1
  • 27
  • 33
jswenson91
  • 21
  • 2
  • 2
    `"vector<{" + obj_name + "}>"` – nhgrif Oct 03 '13 at 21:37
  • possible duplicate of [C++ equivalent of StringBuffer/StringBuilder?](http://stackoverflow.com/questions/2462951/c-equivalent-of-stringbuffer-stringbuilder) – SoapBox Oct 03 '13 at 21:43

4 Answers4

2

If your obj_name is a std::string, you can do what nhgrif suggested

"vector<{" + obj_name + "}>"

If your obj_name is a char [], you can use sprintf which has similar behavior as printf,

int sprintf ( char * str, const char * format, ... );
CS Pei
  • 10,869
  • 1
  • 27
  • 46
1

You can use sprintf() from c:

char buf[1000];
sprintf(buf, "vector<%s>", obj_name);
olegarch
  • 3,670
  • 1
  • 20
  • 19
0

If you miss sprintf in C++ and want to use something more C++'ish, try format from Boost.

#include <iostream>
#include <boost/format.hpp>

using namespace std;
using boost::format;

int main()
{
    string some_string("some string"),
           formated_string(str(format("%1%") % some_string));

    cout << formated_string << endl;

    return 0;
}
Algebraic Pavel
  • 355
  • 3
  • 12
0

You can make a function almost similar to WriteLine from c#:

void WriteLine(string const &outstr, ...) {
    va_list placeholder;
    va_start(placeholder, outstr);
    bool found = false;
    for (string::const_iterator it = outstr.begin(); it != outstr.end(); ++it) {
        switch(*it) {
            case '{':
                found = true;
                continue;
            case '}':
                found = false;
                continue;
            default:
                if (found) printf("%s", va_arg(placeholder, char *));
                else putchar(*it);
        }
    }
    putchar('\n');
    va_end(placeholder);
}

Call it with similar arguements:

WriteLine("My fav place in the world is {0}, and it has a lot of {1} in it", "Russia", "Mountains");

Output:

My fav place in the world is Russia, and it has a lot of Mountains in it

The function is of course not perfect because the System.Console.WriteLine() function from c# can have the arguements not in order and still place the correct strings in the right place in the full string. This can be solved by first placing all the arguements in an array and accessing the index of the array

smac89
  • 39,374
  • 15
  • 132
  • 179