> ## Content Index
> Fetch the complete content index at: https://yinguobing.com/blog/llms.txt
> Use this file to discover other available public pages before exploring further.

# 使用ANSI Escape Code刷新控制行输出
- URL: https://yinguobing.com/blog/using-ansi-escape-code-to-format-output/
- Published: 2017-04-13T11:44:00.000Z
- Updated: 2022-05-29T08:49:56.000Z
- Description: 如果我希望程序在命令行的输出看上去就是在原地刷新，该怎么办？
- Author: 尹国冰
- Tags: Linux

简单的C++程序多采用`printf()`或者`cout <<`的方式来将文本输出到终端窗口。如果我们希望输出的内容刚好处在循环内部的话，你会在终端窗口中看到输出的内容不断增加，将之前的输出“顶”出了窗口，如下图：  
![](https://yinguobing.com/blog/content/images/2017/04/wo-ansi-escape.png)

如果我希望新的输出覆盖旧的输出，看上去就是在原地刷新，如下图，该怎么办？  
![](https://yinguobing.com/blog/content/images/2017/04/w-ansi-escape.png)

此时你需要[**ANCI escap code**](https://en.wikipedia.org/wiki/ANSI%5Fescape%5Fcode?ref=yinguobing.com)。套用一下维基百科上的介绍：

> In computing, ANSI escape codes (or escape sequences) are a method using in-band signaling to control the formatting, color, and other output options on video text terminals.

通过ANCI escap code，我们可以通过直接在C++中输出文本的方式来控制输出在终端中的文本格式。对于本例中来说，循环中的输出共7行，所以我只要在每次循环输出完成后，将光标移动到第一行的开头就OK了。

ANCI escap code中的光标移动代码为`\033[nA`，它会将光标上移n行。所以只要在程序代码中加入一行文本输出语句，即可达到目的。在本例中，循环体内加入的语句是：

```
printf(\033[7A) // 将光标向上移动7行

```

这样即可实现图2中的效果。

如果你想了解更多的ANSI Escape Code，也可以参考[这里](http://www.freeos.com/guides/lsst/misc.htm?ref=yinguobing.com#colorfunandmore)。