【问题标题】:Unexpected console behaviour using '\b' characters使用“\b”字符的意外控制台行为
【发布时间】:2015-10-28 07:48:45
【问题描述】:

我的程序中有这样的代码:

std :: cout << process_prompt << std :: left << std :: setw( 40 ) <<  "Looping on tree: clust_tree.";
some_function();
std :: cout << std :: string( 52, '\b' );

some_function() 有一个循环:

for( Int_t i = 0; i < n_entries; ++i ) 
{
    (some stuff...)
    if( i % 100000 == 0 )
    {
        percent_done = static_cast<float>(i) / n_entries;
        std :: cout << std :: setw( 4 ) << static_cast<int>(percent_done * 100) << "p" << std :: flush;
        std :: cout << std :: string( 5, '\b' ) << std :: flush;
    }
}

process_prompt 只是我用来编写彩色消息“进程:”的一种奇特方式。

我期望发生的是(每一行都是前一行的更新):

Process: Looping on tree: clust_tree.            0   p
Process: Looping on tree: clust_tree.            10  p
...

实际发生的情况:

Process: Looping on tree: clust_tree.            0   p
12  pss: Looping on tree: clust_tree.            0   p
54  pss: Looping on tree: clust_tree.            0   p

不知何故,我的光标总是移动到行的开头。有人可以告诉我我做错了什么吗?感谢您的回复!

发现错误: 我还有一些其他代码部分在循环中输出单个 /b 字符。

【问题讨论】:

  • @Petr 将光标向后移动一个字符,以便我可以更新百分比显示。
  • 什么是Int_t,它与int 有何不同?
  • @LưuVĩnhPhúc 其实是int。
  • 为什么不直接使用int?使用它没有意义。我见过一些 C/C++ 库重新定义了许多 C/C++ 运算符和类型,例如 int、new、try、catch... 像这样
  • 您的代码可以在 Windoze 上与 VC++ v15 配合使用,而 Nim 的“答案”对 GCC 也是如此。您使用的是哪种终端和操作系统?

标签: c++ c++11 console stdout


【解决方案1】:

注意:不是问题的答案,不确定这是否适用于在线编译器,因此此处为完整示例的代码..

这个完整的例子对我来说很好用(c++11,gcc 4.8.2)

#include <iostream>
#include <chrono>
#include <thread>
#include <iomanip>

using namespace std;


int main(void) {
  cout << "Completed " << flush;
  for (auto i = 1; i <= 100; ++i) {
    cout << setw(4) << i << "%" << flush << string(5, '\b') << flush;  
    this_thread::sleep_for(chrono::milliseconds(100));
  }
  cout << endl << "Done" << endl;
}

【讨论】:

    【解决方案2】:

    好的,我似乎找到了答案,实际上每个循环都有一个额外的“/b”。谢谢大家!

    【讨论】:

      猜你喜欢
      • 2014-06-27
      • 2011-10-11
      • 1970-01-01
      • 2014-09-04
      • 2020-09-13
      • 2022-10-25
      • 2011-06-27
      • 1970-01-01
      相关资源
      最近更新 更多