使用'b'字符的意外控制台行为

Unexpected console behaviour using '' characters

本文关键字:控制台 意外 使用 字符      更新时间:2023-10-16

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

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:"。

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

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字符。

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

这个完整的例子对我来说很好(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;
}

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