Lion King
Lion King

Reputation: 33823

is there another way except stringstream, to concatenate a string consist of more than type of variables?

When we need to concatenate a string with data from more than one variable type, we usually do the following:

int year = 2013;
float amount = 385.5;

stringstream concat;
string strng;
concat << "I am in the year " << year << " and I don't have in my pocket but the amount " << amount;
strng = concat.str();

cout << strng << endl;

As we see in that code, we concatenate many types of data: year is int type, amount is a float and the string I am in the year is a string type. In other programming languages you can do the same by using the + operator.

So, going back to the question: Is there another way except stringstream, to concatenate a string (char or string type) while inputting data from more than one type of variable in C and C++ languages? I'd like to be able to do it in both languages.

Upvotes: 0

Views: 400

Answers (2)

jxh
jxh

Reputation: 70502

You can use vsnprintf() to implement a kind of wrapper to print into a string that is dynamically expanded as needed. On Linux, a C solution exists in the form of asprintf(), and it returns memory that has to be released with free():

char *concat;
asprintf(&concat, "I am in the year %d and I don't have in my pocket but the amount %f",
         year, amount);
std::string strng(concat);
free(concat);

In C++, you can implement something a little more use friendly, since RAII can take care of memory management issues for you:

int string_printf (std::string &str, const char *fmt, ...) {
    char buf[512];
    va_list ap;
    va_start(ap, fmt);
    int r = vsnprintf(buf, sizeof(buf), fmt, ap);
    va_end(ap);
    if (r < sizeof(buf)) {
        if (r > 0) str.insert(0, buf);
        return r;
    }
    std::vector<char> bufv(r+1);
    va_start(ap, fmt);
    r = vsnprintf(&bufv[0], bufv.size(), fmt, ap);
    va_end(ap);
    if (r > 0) str.insert(0, &bufv[0]);
    return r;
}


std::string strng;
string_printf(strng,
              "I am in the year %d and I don't have in my pocket but the amount %f",
              year, amount);

Upvotes: 1

Lochemage
Lochemage

Reputation: 3974

Using stringstream is certainly very convenient, but not the only way. One way is to use sprintf() and another is to convert all value types to strings via methods like itoa() or ftoa() and use the standard string concatination method strcat() to combine multiple strings together.

Upvotes: 2

Related Questions