我创建了一个循环,因为循环很长,所以我想看看进度。因此,我添加了一些退格字符以在同一行上打印循环的百分比:
std::size_t photoCntr = 0;
for (std::vector< VerifObj >::const_iterator itVOV = verifObjVector.begin(); itVOV != verifObjVector.end(); itVOV++)
{
// some operations
std::cout << "\b\b\b\b" << std::setw(3) << static_cast< int >(100.f * ++photoCntr / verifObjVector.size()) << "%";
}
在控制台中,直到循环结束才进行任何打印,然后再进行打印100%
。循环需要很长时间(几分钟)。我正在使用Ubuntu 14.04和g ++ 11。可能是某种优化直到缓冲区装满后才打印吗?关于如何使其运作的任何想法?
您需要刷新输出缓冲区:
std::cout.flush();
您也可以使用以下样式:
std::cout << "Stuff" << std::flush;
只是为了彻底,这个完整的程序在地方上显示出越来越大的进步:
#include <iostream>
#include <iomanip>
#include <chrono>
#include <thread>
int main() {
for (int i=0; i<100; ++i) {
std::cout << "\b\b\b\b" << std::setw(3) << i << '%' << std::flush;
std::this_thread::sleep_for(std::chrono::milliseconds(30));
}
std::cout << "\b\b\b\b100%" << std::endl;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句