【问题标题】:Postpone standard output in the end最后推迟标准输出
【发布时间】:2018-05-05 16:41:40
【问题描述】:

在此过程中可能会打印出许多警告消息(通过std::cout)。有没有办法推迟打印程序结束时发出的警告消息?有海量的加工信息会被打印出来。我计划最终将所有警告放在一起,而不是分散在各处。

更多背景:

  1. 代码已经存在。
  2. 代码中有大约 50 条警告消息(如果有某种 delay( ) 函数,我不想添加 50 次,如果有一个全局延迟/延迟函数用于stand就好了输出)

谢谢

【问题讨论】:

  • 你可以使用一个 std::stringstream 来保存你想要推迟的内容,然后在末尾显示它 "std::cout
  • 警告信息和错误信息应该写到std::cerrstd::clog。正常输出到std::cout。这样你就可以重定向一个或另一个输出流(通常是标准错误),这样它的输出就不会与另一个流的混合。

标签: c++ stdout


【解决方案1】:

一种方法是将所有内容发送到stringstream,然后在最后打印。

例如:

#include <iostream>
#include <sstream>

int main(){
    int i = 5, j = 4;
    std::stringstream ss;
    std::cout << i * j << std::endl;
    ss << "success" << std::endl;
    std::cout << j + i * i + j << std::endl;
    ss << "failure" << std::endl;
    std::cout << ss.str() << std::endl;
    return 0;
}

输出:

20                                                                                                                    
33                                                                                                                    
success                                                                                                               
failure 

【讨论】:

  • 唯一的问题是,如果你已经是个傻瓜并且到处使用std::cout
  • @NickChapman There are huge amount of the processing information will be printed. I'm planing to have all the warnings together in the end rather than scattered around 我在复制问题要求。
【解决方案2】:

如果您只是想延迟std::cout 的所有打印,您可以做的是将标准输出重定向到充当缓冲区的字符串流。它非常简单,避免了所有可能倾向于尝试的dupdup2 和管道。

#include <sstream>

// Make a buffer for all of your output
std::stringstream buffer;
// Copy std::cout since we're going to replace it temporarily
std::streambuf normal_cout = std::cout.rdbuf();
// Replace std::cout with your bufffer
std::cout.rdbuf(buffer.rdbuf());

// Now your program runs and does its thing writing to std::cout
std::cout << "Additional errors or details" << std::endl;

// Now restore std::cout
std::cout.rdbuf(normal_cout);
// Print the stuff you buffered
std::cout << buffer.str() << std::endl;

同样,在未来,您应该从一开始就真正使用缓冲区来处理错误,或者至少写入错误并记录到std::cerr,这样您的正常运行时打印输出就不会因错误而杂乱无章。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-18
    • 1970-01-01
    • 2017-07-21
    • 2021-10-20
    • 1970-01-01
    相关资源
    最近更新 更多