如何在cout中定义自己的特殊角色

时间:2019-03-04 19:13:16

标签: c++ stdout cursor-position

例如:

cout << "  hello\n400";

将打印:

  hello
400

另一个例子:

cout << "  hello\r400";

将打印:

400ello

是否可以定义自己的特殊角色? 我想做点什么:

cout << "  hello\d400";

将给出:

  hello
  400

(/ d是我的特殊字符,我已经有了将stdout光标向下移动一行的功能(cursorDown()),但是我只是不定义每次写入的特殊字符调用我的cursorDown()函数)

2 个答案:

答案 0 :(得分:2)

正如其他人所说,您无法让cout理解用户定义的字符,但是您可以做的是

  • std :: cout是类型为std :: ostream的对象,该对象会使operator <<重载。您可以创建该结构的对象,该对象在使用类似于任何日志流的ostream将其打印到文件或控制台之前,将字符串解析为特殊字符和其他用户定义的字符。 Example

  • 代替致电cout << "something\dsomething" 您可以调用方法special_cout(std::string);来解析用户定义字符的字符串并执行调用。

答案 1 :(得分:1)

无法定义“新”特殊字符。

但是您可以使流解释特定字符以具有新的含义(可以定义)。您可以使用本地人来做到这一点。

一些注意事项:

字符串"xyza"中的字符只是编码字符串的一种简单方法。转义字符是C ++的一种允许您表示不可见但定义明确的字符的方式。查看ASCII表,您会发现00 -> 31范围内的所有字符(十进制)都有特殊含义(通常称为控制字符)。

在此处查看:http://www.asciitable.com/

您可以使用转义序列将任何字符放入字符串中以指定其确切值;也就是说,在字符串中使用\x0A会将“ New Line”字符放入字符串中。

更常用的“控制字符”具有简写版本(由C ++语言定义)。 '\n' => '\x0A',但您不能添加新的特殊速记字符,因为这只是该语言的一种便利功能(就像大多数语言所支持的传统一样)。

但是给定一个字符,您可以在IO流中赋予它特殊的含义。 。您需要为语言环境定义一个方面,然后将该语言环境应用于流。

注意:现在将本地人应用于std::cin / std::out时出现问题。如果已使用流(以任何方式),则应用本地可能会失败,并且操作系统可能会在您到达main()之前对流进行处理,从而将语言环境应用于std::cin / {{1} }可能会失败(但是您可以轻松地对文件流和字符串流进行处理)。

那我们该怎么做。

让我们使用“垂直制表符”作为我们要更改其含义的字符。我之所以选择它,是因为它有一个std::cout的快捷方式(因此它的键入比\v短),并且通常对终端没有任何意义。

让我们将含义定义为换行并缩进3个空格。

\x0B

一些使用语言环境的代码。

#include <locale>
#include <algorithm>
#include <iostream>
#include <fstream>

class IndentFacet: public std::codecvt<char,char,std::mbstate_t>
{
  public:
   explicit IndentFacet(size_t ref = 0): std::codecvt<char,char,std::mbstate_t>(ref)    {}  

    typedef std::codecvt_base::result               result;
    typedef std::codecvt<char,char,std::mbstate_t>  parent;
    typedef parent::intern_type                     intern_type;
    typedef parent::extern_type                     extern_type;
    typedef parent::state_type                      state_type;

  protected:
    virtual result do_out(state_type& tabNeeded,
                         const intern_type* rStart, const intern_type*  rEnd, const intern_type*&   rNewStart,
                         extern_type*       wStart, extern_type*        wEnd, extern_type*&         wNewStart) const
    {   
        result  res = std::codecvt_base::ok;

        for(;(rStart < rEnd) && (wStart < wEnd);++rStart,++wStart)
        {   
            if (*rStart == '\v')
            {   
                if (wEnd - wStart < 4)
                {   
                    // We do not have enough space to convert the '\v`
                    // So stop converting and a subsequent call should do it.
                    res = std::codecvt_base::partial;
                    break;
                }   
                // if we find the special character add a new line and three spaces
                wStart[0] = '\n';
                wStart[1] = ' ';
                wStart[2] = ' ';
                wStart[3] = ' ';

                // Note we do +1 in the for() loop
                wStart += 3;
            }   
            else
            {
                // Otherwise just copy the character.
                *wStart             = *rStart;
            }   
        }   

        // Update the read and write points.
        rNewStart   = rStart;
        wNewStart   = wStart;

        // return the appropriate result.
        return res;
    }   

    // Override so the do_out() virtual function is called.
    virtual bool do_always_noconv() const throw()
    {   
        return false;   // Sometime we add extra tabs
    }   

};

输出:

int main()
{
    std::ios::sync_with_stdio(false);

    /* Imbue std::cout before it is used */
    std::cout.imbue(std::locale(std::locale::classic(), new IndentFacet()));

    // Notice the use of '\v' after the first lien
    std::cout << "Line 1\vLine 2\nLine 3\n";

    /* You must imbue a file stream before it is opened. */
    std::ofstream       data;
    data.imbue(std::locale(std::locale::classic(), new IndentFacet()));
    data.open("PLOP");

    // Notice the use of '\v' after the first lien
    data << "Loki\vUses Locale\nTo do something silly\n";
}

但是

现在写所有这些都不是值得的。如果您想要像这样的固定缩进,我们将使用一个包含这些特定字符的命名变量。它使您的代码更加冗长,但是可以解决问题。

> ./a.out
Line 1
   Line 2
Line 3
> cat PLOP
Loki
   Uses Locale
To do something silly
相关问题