【问题标题】:Display escape sequences as text only仅将转义序列显示为文本
【发布时间】:2023-03-24 07:34:01
【问题描述】:

我的程序输出的文本有时包含转义序列,例如“\x1B[J”(清屏)。有没有办法抑制转义序列,使其不执行相关操作,而是通过其文本表示形式显示?

我什至有兴趣为 \n 和 \r 这样做。

【问题讨论】:

  • 如何输出文本?例如echo -e "something" 会执行它,而echo -e "something" 不会。
  • @fedorqui 我有一个写入标准输出的 C++ 程序
  • 输入从何而来?

标签: c++


【解决方案1】:

通过将每个出现的字符更改为 \\ 来转义 \ 字符。

请注意,这些序列仅在您将它们输入源代码时才有效。检查以下程序的结果:

#include <cstdio>

int main(int argc, char * argv[])
{
    char test[3] = { 0x5c, 0x6e, 0x00 }; // \n
    char * test2 = "\\n"; // \n

    printf("%s\n", test);
    printf("%s\n", test2);
    printf(test);
    printf(test2);

    return 0;
}

【讨论】:

  • 我认为他说的不是 C++ 字符转义(`` 字符),而是用于屏幕处理的传统 ANSI 转义码。这些总是以 ESC 字符 (0x1B) 开头,以字母结尾,因此您需要某种逻辑来识别序列。
  • 我明白,他想在屏幕上显示一个字符串\x1B[J。在这种情况下,将 \ 转义到 \\ 应该可以工作。但是,如果解析器已经将该字符串转换为转义序列,则确实需要另一种方法。
【解决方案2】:

目前尚不清楚您要在哪个级别进行干预。如果你是 编写输出,最简单的解决方案就是不插入 开头的字符。如果你通过一个 std::ostream 到某个库,它正在插入 字符,插入过滤streambuf相当简单 进入输出流,并将它们过滤掉。类似的东西 以下应该可以解决标准转义序列:

class EscapeSequenceFilter
{
    std::streambuf* myDest;
    std::ostream* myOwner;
    bool myIsInEscapeSequence;

protected:
    int overflow( int ch )
    {
        int retval = ch == EOF ? ch : 0;
        if ( myIsInEscapeSequence ) {
            if ( isalpha( ch ) ) {
                myIsInEscapeSequence = false;
        } else if ( ch == 0x1B ) {
            myIsInEscapeSequence = true;
        } else {
            retval = myDest->sputc( ch );
        }
        return retval;
    }

public:
    EscapeSequenceFilter( std::streambuf* dest )
        : myDest( dest )
        , myOwner( NULL )
        , myIsInEscapeSequence( false )
    {
    }
    EscapeSequenceFilter( std::ostream& dest )
        : myDest( dest.rdbuf() )
        , myOwner( &dest )
        , myIsInEscapeSequence( false )
    {
        myOwner->rdbuf( this );
    }
    ~EscapeSequenceFilter()
    {
        if ( myOwner != NULL ) {
            myOwner->rdbuf( myDest );
        }
    }
};

只需声明这个类的一个实例,输出流为 调用要过滤的函数之前的参数。

这个类很容易扩展来过滤你的任何其他字符 可能希望。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-19
    相关资源
    最近更新 更多