经常会遇到将数据解析为文本文件的现象,通常因为数据长度的不同导致,可视化效果不好。
写一个输入数据获取固定长度字符串的函数,来得到一个固定长度的数据,让格式化看起来好看一些。
#include <type_traits>
#include <sstream>
#include <typeinfo>
template<typename T>
std::string gen_fixed_len_str(T val, uint64_t len)
{
std::ostringstream oss;
if (true == std::is_arithmetic<T>::value ||
/// std::string const std::string std::string& const std::string& 的typeid是一样的
typeid(val).name() == typeid(std::string).name() ||
typeid(val).name() == typeid(char*).name() ||
typeid(val).name() == typeid(const char*).name()) {
oss << val;
}
if (oss.str().size() > len) {
return oss.str().substr(0, len);
}
else {
for (std::size_t i = oss.str().size(); i < len; ++i) {
oss << " ";
}
}
return oss.str();
}
使用snprintf的格式化
snprintf使用也很方便,举个下边的简单的例子
char buf[64] = {0};
// abc 占10个字符的位置 右对齐
std::snprintf(buf, sizeof (buf), "%10s", "abc");
char buf1[64] = {0};
// abc 占10个字符的位置 左对齐
std::snprintf(buf1, sizeof (buf1), "%-10s", "abc");
//需要注意的是,如果字符串的长度超过了设置的宽度,那么设置的宽度就无效了。
//整型数据的输出是一样的
stringstream加上std::setw函数来实现。
std::ostringstream oss;
oss << std::left
<< std::setw(10) << "abc"
<< std::right
<< std::setw(15) << 100
<< std::endl;
std::cout << oss.str();
//涉及到的头文件包括
// #include <sstream>
// #include <ios>
// #include <iomanip>
// 如果需要不足的位置补上一些字符的话可以使用 std::setfill('0') 比如补0
这种风格的输出也很优雅。一样的问题是设置的宽度不够的时候,宽度就无效了。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)