Reputation: 27
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
Upvotes: 0
Views: 1411
Reputation: 2185
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';
Upvotes: 3
Reputation: 490328
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);
}
Upvotes: 6