我正在使用 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/