C++ 将snprintf替换为c++;串
我需要用C++ 将snprintf替换为c++;串,c++,c,stdstring,printf,C++,C,Stdstring,Printf,我需要用std::string替换使用snprintf的C字符缓冲区,并对它们执行相同的操作。我被禁止使用stringstream或boost库 有办法吗 const char *sz="my age is"; std::string s; s=sz; s+=100; printf(" %s \n",s.c_str()); 我得到的输出为 my age is d 其中所需输出为: my age is 100 按如下所示编辑代码 const char *sz="my age is"; st
std::string
替换使用snprintf
的C字符缓冲区,并对它们执行相同的操作。我被禁止使用stringstream
或boost
库
有办法吗
const char *sz="my age is";
std::string s;
s=sz;
s+=100;
printf(" %s \n",s.c_str());
我得到的输出为my age is d
其中所需输出为:my age is 100
按如下所示编辑代码
const char *sz="my age is";
std::string s{sz};
s+=std::string{" 100"};
std::cout << s << '\n';
这正是
stringstream
s发明的工作类型,因此排除它们似乎相当愚蠢
尽管如此,是的,你可以很容易地在没有它们的情况下做到:
std::string s{" my age is "};
s += std::to_string(100);
std::cout << s << " \n";
#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);
}
@DominikC:C++11的可用性非常广泛,除非指定了其他版本,否则我将其视为“C++”的同义词。@Jeffry:谢谢你的帮助。但正如Dominik所说,原来我所在的编译器太旧了,不支持to_字符串。@BasavNagar:有关如何编写自己的转换的基本概念,请参见编辑。@Jeffry:你说得对。我想我现在必须编写自己的转换。@BasavNagar:
stringstream
s是做这种“东西”的“实用工具”。。。。你的要求禁止使用字符串不是很“奇怪”吗?是的,这会起作用,也是避免使用字符串的一种方法,因为我的编译器不支持它。这无助于处理编译时数字位于未知值的变量中的情况。@TonyD:我编辑了这篇文章来处理你说的情况。+1来自我。。。干杯(一般来说,snprintf(
将整个结果放入一个大小足够的缓冲区,然后在此基础上构造一次返回字符串)可能更容易.实际上,我理解boost的情况,但为什么禁止使用stringstream?它们都在std::stringstream不是库扩展,它与字符串本身在同一个标准库中。我是说库扩展或头文件。字符串流在不同的头文件中,不是吗??
#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);
}