对要打印到终端的字符串进行消毒的惯用方法

idiomatic way to sanitize a string for printing to a terminal?

本文关键字:方法 字符串 打印 终端      更新时间:2023-10-16

我在内存中有这个字符串,我想把它打印到终端或日志文件中——不要得到垃圾/不可打印的字符,因为这会影响我的风格。所以,不用

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。你可以用它来检查字符串中的一个字符是否是可打印的,如果它是可打印的,让它打印这个字符如果它不是,它什么都不做。