我正在使用boost::format
(而不是std::
因为我正在使用c ++ 98)来格式化我传递给system()
调用的字符串。
获取c_str()
创建的字符串的format
时,它似乎在字符串的中途终止。使用文字值创建的相同sting没有相同的问题。这是怎么回事?
根据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 `''
大概是因为它也沿着琴弦中途完成了。
答案 0 :(得分:0)
正确包含您的程序正常工作: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)
}
您应修复包含并返回主要类型,然后重试。如果错误的行为持续存在,则可能是您破坏了c ++和/或boost库的版本。