使用退格控制字符擦除 [英] Erasing using backspace control character

查看:128
本文介绍了使用退格控制字符擦除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使用退格控制字符'\b'来删除行末尾的逗号。虽然它适用于没有其他输出到 stdout 的情况下,如果'\b',它变得无用。下面是一个例子:

I am trying to use the backspace control character '\b' to erase trailing commas at the end of line. Although it works in cases where there is no other output to stdout, in case if there is another output after '\b', it becomes useless. Here is an example:

#include <iostream>

using namespace std;

int main()
{
    int a[] =  { 1, 3, 4, 5, 6, 32, 321, 9};
    for ( int i = 0; i < 8; i++) {
        cout << a[i] << "," ;
    }
    cout << "\b" ;
    //cout << endl;
    return 0;
}

在上面的代码块中,如果行被注释为获得所需的结果,在数字9后面没有逗号。但是,如果该行未注释,则逗号重新出现。

In the above block of code, if the line is commented as seen, we get the desired result with no comma after the digit 9. However, if the line uncommented, the comma re-appears.

在我的程序中,我不希望逗号在那里,但希望在9之后有一个结束。我该怎么做?

In my program, I do not want the comma to be there, but want an endline after 9. How do I do this ?

推荐答案

删除控制台上最后一个字符的常用方法是使用序列\b \b。这会将光标向后移动一个空格,然后写一个空格以删除字符,并重新使用反空格,以便新的写入从旧位置开始。注意, \b 本身只移动光标。

The usual way of erasing the last character on the console is to use the sequence "\b \b". This moves the cursor back one space, then writes a space to erase the character, and backspaces again so that new writes start at the old position. Note that \b by itself only moves the cursor.

当然,你可以避免输出逗号在第一位:

Of course, you could always avoid outputting the comma in the first place:

if(i > 0) cout << ",";
cout << a[i];

这篇关于使用退格控制字符擦除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆