gpt4 book ai didi

c++ - {fmt}等同于cout.rdbuf?

转载 作者:行者123 更新时间:2023-12-02 10:23:02 29 4
gpt4 key购买 nike

我有一个单元测试,它通过读取函数发送的缓冲区来验证函数:

template <typename Manifold>
void print_manifold(Manifold const& manifold)
try
{
std::cout << "Manifold has " << manifold.N0() << " vertices and "
<< manifold.N1() << " edges and " << manifold.N2() << " faces and "
<< manifold.N3() << " simplices.\n";
// fmt::print(
// "Manifold has {} vertices and {} edges and {} faces and {}
// simplices.\n", manifold.N0(), manifold.N1(), manifold.N2(),
// manifold.N3());
}
catch (...)
{
std::cerr << "print_manifold() went wrong ...\n";
throw;
} // print_manifold

和:
SCENARIO("Printing results", "[utility]")
{
// redirect std::cout
stringstream buffer;
cout.rdbuf(buffer.rdbuf());
GIVEN("A Manifold3")
{
Manifold3 const manifold(640, 4);
WHEN("We want to print statistics on a manifold.")
{
THEN("Statistics are successfully printed.")
{
print_manifold(manifold);
CHECK_THAT(buffer.str(), Catch::Contains("Manifold has"));
}
}
}

有没有办法捕获由 fmt::print生成的输出到 stdout的输出?

当我注释掉 cout代码并取消注释 fmt代码时,我得到了由 cout <<的先前实例产生的缓冲区。

最佳答案

这比{fmt}问题更像是一个C stdio问题,但是您可以按照Redirecting stdout to pipe in C的答案中所述将stdout重定向到管道并从中读取输出。尽管这不是一个好的单元测试,因为它取决于全局状态,但是您当前的测试也存在相同的问题。

关于c++ - {fmt}等同于cout.rdbuf?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59231840/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com