在使用中发现输出有乱码的问题,代码如下:
#include <iostream>
#include <boost/program_options.hpp>
namespace po = boost::program_options;
po::variables_map vm;
void main(int argc, char** argv)
{
std::locale::locale(std::locale(""));
try
{
// 声明被支持的选项。
po::options_description desc("All options", 500);
desc.add_options()
("help,h", ("检查一个文件的数据"))
("file,f", po::value<std::string>(), ("需要检查的文件的全路径名"))
("type,t", po::value<int>(), ("需要检查的文件的类型:.第一文件;2.第二文件;3.第三文件。4.aaaaaa文件"));
//解析并保存命令行参数
po::store(po::parse_command_line(argc, argv, desc), vm);
po::notify(vm);
if (vm.count("help"))
{
std::cout << desc << "\n";
}
}
catch (const std::exception&)
{
std::cout << "未知的命令行参数" << "\n";
}
}
结果有乱码出现
All options: -h [ --help ] 检查一个文件的数据 -f [ --file ] arg 需要检查的文件的全路径名 -t [ --type ] arg 需要检查的文件的类型:1.第一文件;2.第二文件;3.第三文 ?. aaaaaa文件
经排查,问题的原因在于以下几点;
1. 没有设置
std::locale::locale(std::locale(""));
2. 没有设置打印宽度
po::options_description desc("All options", 500);
这个宽度是汉字个数的2倍,也有可能是3倍。需要长一点才能避免自动换行。
3. 字符串超过了默认的换行长度24。这个长度应该是boost库自己计算得到的。其实现如下:
void
options_description::print(std::ostream& os, unsigned width) const
{
if (!m_caption.empty())
os << m_caption << ":\n";
if (!width)
width = get_option_column_width();
/* The options formatting style is stolen from Subversion. */
for (unsigned i = 0; i < m_options.size(); ++i)
{
if (belong_to_group[i])
continue;
const option_description& opt = *m_options[i];
format_one(os, opt, width, m_line_length);
os << "\n";
}
for (unsigned j = 0; j < groups.size(); ++j) {
os << "\n";
groups[j]->print(os, width);
}
}
因此,在字符串中换行,也可以规避这个问题:
"需要检查的文件的类型:1.第一文件;2.第二文件;3.第三\n文件""