繁体   English   中英

用C ++字符串替换snprintf

[英]replacing snprintf with c++ strings

我需要使用snprintfstd::string替换C char缓冲区,并对它们执行相同的操作。 我被禁止使用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);
}

如下编辑代码,

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

您需要将字符串连接为字符串,而不是整数。
如果年龄在不同的运行中有所不同,则可以使用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.

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