c++ - 在 C++ 中使用 sprintf 和 std::string

标签 c++ string c++11

我在 C++ 11 中使用 sprintf 函数,方式如下:

std::string toString()
{
    std::string output;
    uint32_t strSize=512;
    do
    {
        output.reserve(strSize);
        int ret = sprintf(output.c_str(), "Type=%u Version=%u ContentType=%u contentFormatVersion=%u magic=%04x Seg=%u",
            INDEX_RECORD_TYPE_SERIALIZATION_HEADER,
            FORAMT_VERSION,
            contentType,
            contentFormatVersion,
            magic,
            segmentId);

        strSize *= 2;
    } while (ret < 0);

    return output;
}

除了每次检查预留空间是否足够之外,还有更好的方法吗?为了将来添加更多东西的可能性。

最佳答案

您的构造 -- 写入 到从 c_str() 接收的缓冲区中 -- 是 未定义的行为,即使您检查了字符串的容量预先。 (返回值是一个指向 const char 的指针,函数本身标记为 const,这是有原因的。)

不要混合使用 C 和 C++,尤其是不适合写入内部对象表示。 (这破坏了非常基本的 OOP。)使用 C++,以确保类型安全,并且不会遇到转换说明符/参数不匹配,如果没有别的原因。

std::ostringstream s;
s << "Type=" << INDEX_RECORD_TYPE_SERIALIZATION_HEADER
  << " Version=" << FORMAT_VERSION
  // ...and so on...
  ;
std::string output = s.str();

替代方案:

std::string output = "Type=" + std::to_string( INDEX_RECORD_TYPE_SERIALIZATION_HEADER )
                   + " Version=" + std::to_string( FORMAT_VERSION )
                   // ...and so on...
                   ;

关于c++ - 在 C++ 中使用 sprintf 和 std::string,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36908994/

相关文章:

c++ - 如何使语言友好功能降低?

python - 如何将 numpy 对象数组转换为 str/unicode 数组?

string - 在 R 中以 "V, W, X, Y, and Z"样式输出列表的简单方法

c++ - 来自元组的构造函数参数

c++ - 使用 STL std::merge() 将 vector 的两个部分合并到另一个 vector 中

c++ - 谷歌测试中的使用线程

c++ - 是否可以使用 cv::VideoCapture 加载 32 位帧

python - 使用 stdout stdin 将数组从 C++ exe 传递到 Python

java - stringTokenizer java 的克隆值

c++ - 类成员标识符的解析如何在 C++ 中工作