简体   繁体   中英

replacing snprintf with c++ strings

I have a requirement to replace C char buffers using snprintf with std::string and perform the same operation on them. I am forbidden from using stringstream or boost library.

Is there a way to do it?

const char *sz="my age is";
std::string s;
s=sz;
s+=100;
printf(" %s \n",s.c_str());

I get the output as

my age is d 

where as required output is:

my age is 100

This is exactly the sort of job for which stringstream s were invented, so ruling them out seems fairly silly.

Nonetheless, yes, you can do it without them pretty easily:

std::string s{" my age is "};

s += std::to_string(100);

std::cout << s << " \n";

If you're stuck with an older compiler that doesn't support to_string , you can write your own pretty easily:

#include <string>

std::string to_string(unsigned in) { 
    char buffer[32];
    buffer[31] = '\0';
    int pos = 31;

    while (in) {
        buffer[--pos] = in % 10 + '0';
        in /= 10;
    }
    return std::string(buffer+pos);
}

Edit your code as below,

const char *sz="my age is";
std::string s{sz};
s+=std::string{" 100"};
std::cout << s << '\n';

You need to concat a string to a string, not an integer to a string.
If the age is varied in different runs, you can use sprintf to make a string from it and then, append to string s .

std::string s{" my age is "};
int age = 30;
char t[10] = {0};
sprintf(t, "%d", age);
s += std::string{t};
std::cout << s << '\n';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM