c++ - 为什么 std/boost::format 会导致这种 c_str() 行为?

标签 c++ boost std

我正在使用 boost::format(不是 std::,因为我正在使用 c++98)来格式化我传递给的字符串system() 调用。

当获取由format 创建的字符串的c_str() 时,它似乎在字符串中途终止。使用文字值创建的相同字符串不会出现相同的问题。这是怎么回事?

根据 BOOST_VERSION 使用 Boost 1.46.1

#include <boost/format.hpp>
#include <iostream>
#include <string>

int main(int argc, char** argv)
{
    const std::string my_str = "echo '/%1%/ some other stuff'";
    boost::format fmtr(my_str);
    fmtr % "sleep 3";   // should read: echo '/sleep 3/ some other stuff'

    std::cout << "1: " << fmtr.str() << "\n";          // 1. echo '/sleep 3/ some other stuff'  (OK)
    std::cout << "2: " << fmtr.str().c_str() << "\n";  // 2. echo '/sleep 3                     (BAD)

    // Try the c_str of a string not created through boost::format
    const std::string finished = "echo '/sleep 3/ some other stuff'";
    std::cout << "3: " << finished.c_str() << "\n";    // 3. echo '/sleep 3/ some other stuff'  (OK)

    // Try copying the string from format to see if that makes any difference (it doesn't)
    std::string copy = fmtr.str();
    std::cout << "4: " << copy.c_str() << "\n";        // 4. echo '/sleep 3                     (BAD)
    return 0;
}

c_str() 传递到我的 system() 调用导致错误:

sh -c: line 0: unexpected EOF while looking for matching `''

大概是因为它也在字符串的中途完成。

最佳答案

有了适当的包含你的程序工作正常:ideone

#include <boost/format.hpp>
#include <iostream>
#include <string>

int main()
{
    const std::string my_str = "echo '/%1%/ some other stuff'";
    boost::format fmtr(my_str);
    fmtr % "sleep 3";   // should read: echo '/sleep 3/ some other stuff'

    std::cout << "1: " << fmtr.str() << "\n";          // 1. echo '/sleep 3/ some other stuff'  (OK)
    std::cout << "2: " << fmtr.str().c_str() << "\n";  // 2. echo '/sleep 3                     (BAD)

    // Try the c_str of a string not created through boost::format
    const std::string finished = "echo '/sleep 3/ some other stuff'";
    std::cout << "3: " << finished.c_str() << "\n";    // 3. echo '/sleep 3/ some other stuff'  (OK)

    // Try copying the string from format to see if that makes any difference (it doesn't)
    std::string copy = fmtr.str();
    std::cout << "4: " << copy.c_str() << "\n";        // 4. echo '/sleep 3                     (BAD)
}

您应该修复 main 的包含和返回类型,然后重试。如果错误行为仍然存在,很可能是您的 C++ 和/或 boost 库版本损坏。

关于c++ - 为什么 std/boost::format 会导致这种 c_str() 行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38355640/

相关文章:

c++ - boost::mpl:如何为超过 50 个条目的列表生成预生成的头文件?

c++ - 使用 gprof 和 boost

c++ - std::future::get() 不捕获异步函数抛出和程序崩溃时的异常

c++ - std::map::iterator 在增量时使程序崩溃

c++ - PETSC DMDA vec 值分配给 wrang 位置

C++从模板函数编译时间数组大小

c++ - 使用 boost property_tree 创建 json 数组

c++ - 为什么使用 std::make_* 而不是构造函数更好?

c++ - 当方法可用时,我如何专门化模板?

c++ - 安装 BLAS 时遇到问题,以及 CMakeLists 的用途?