对要打印到终端的字符串进行消毒的惯用方法
idiomatic way to sanitize a string for printing to a terminal?
我在内存中有这个字符串,我想把它打印到终端或日志文件中——不要得到垃圾/不可打印的字符,因为这会影响我的风格。所以,不用
my_output_stream << my_string;
我想做
my_output_stream << sanitize(my_string);
或者
sanitize_to(my_output_stream, my_string);
是否有一些习惯的/标准的工具来做这件事?
习惯做法是过滤不可打印文件。
我知道没有现有的方法,但很容易写一个:看它Live On Coliru
#include <cctype>
#include <iostream>
#include <sstream>
#include <string>
#include <iomanip>
template <typename It>
std::string sanitize(It f, It l) {
std::ostringstream oss;
for (;f!=l;++f)
{
if((std::isgraph(*f) || std::isspace(*f)) && *f != 'r' && *f != 'n')
oss << *f;
else
oss << "%" << std::hex << std::setw(2) << std::setfill('0') <<
static_cast<unsigned>(static_cast<unsigned char>(*f));
}
return oss.str();
}
template <typename C>
std::string sanitize(C const& c) {
using std::begin;
using std::end;
return sanitize(begin(c), end(c));
}
int main()
{
std::cout << sanitize("Hellotworldrn. §1.3 b") << "n";
}
cctype库有一个isprint()函数,如果字符是可打印的,则返回true。你可以用它来检查字符串中的一个字符是否是可打印的,如果它是可打印的,让它打印这个字符如果它不是,它什么都不做。
相关文章:
- 有哪些有效的方法可以消除一组 100 万个字符串>重复数据?
- 在 c++ 中对类中的 c 字符串动态数组进行排序的最佳方法是什么?
- 具有字符串化的可变参数宏的现代/通用方法
- 接收字符串并使用它来调用方法C++
- 如何分隔字符串并将标记传递给方法
- 是否有通用方法可以找到任何以 null 结尾的字符串的长度?
- 当映射包含字符串向量作为值时,从值中获取键的有效方法
- 在 C++11 中字符串化变量名称的替代方法
- 连接和压缩标准::vector<std::字符串的最佳方法>
- Esp8266 & Nodemcu:返回请求字符串的方法
- 将位字符串转储到二进制文件的最佳方法是什么
- 有没有一种 STL 方法可以找到字符串的所有排列,给出一个以 C++ 为单位的大小?
- 如何将字符串从 C++/CLI 方法返回到调用它的非托管C++
- 创建字符串数组的有效方法
- 如何使用字符串::replace方法写入文件
- 是否有更有效的方法来生成日期的REGEX字符串
- C++-将对象(如字符串)映射到表中成员函数的正确方法
- 有没有更快的方法从成员函数返回格式化字符串
- 有没有一种方法可以在不复制数据的情况下从string_view创建字符串流
- 从c++中的类指针对象调用方法(字符串)