[英]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. 我需要使用snprintf
和std::string
替换C char缓冲区,并对它们执行相同的操作。 I am forbidden from using stringstream
or boost
library. 我被禁止使用stringstream
或boost
库。
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. 这正是发明stringstream
的工作,因此排除它们似乎很愚蠢。
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: 如果您使用的旧编译器不支持to_string
,则可以轻松编写自己的编译器:
#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
. 如果年龄在不同的运行中有所不同,则可以使用sprintf
从中生成一个字符串,然后追加到字符串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';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.