c++ - 用 C++ 字符串替换 snprintf

标签 c++ c stdstring printf

我需要用 std::string 替换使用 snprintf 的 C 字符缓冲区,并对它们执行相同的操作。我被禁止使用 stringstreamboost 库。

有办法吗?

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

最佳答案

这正是发明 stringstream 的工作类型,因此将它们排除在外似乎相当愚蠢。

不过,是的,没有它们你也可以很容易地做到这一点:

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

s += std::to_string(100);

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

如果您受困于不支持 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);
}

关于c++ - 用 C++ 字符串替换 snprintf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20627280/

相关文章:

c++ - 使用 gnuplot 动态绘制 volatile 数据文件

c++将地址位置视为整数

C - 检查矩阵[x][y]周围的位置

c++ - 将 System::String 转换为 std::string 时,std::string delete 运算符出现运行时异常

c++ - std::cin >> std::string 是如何实现的?

c++ - 将 std::lower_bound 与 std::vector::const_iterator 一起使用

c++ - 在 Boost.ProgramOptions 中使用类似 gettext 的翻译

c - 在没有库的情况下将 JVM 嵌入 C 程序的推荐方法?

c - 如何开发这个算法?

c++ - 除非通过引用传递,否则字符串类型无法正常工作