gpt4 book ai didi

c++ - 重定向 cout -> std::stringstream,没有看到 EOL

转载 作者:太空狗 更新时间:2023-10-29 21:30:48 27 4
gpt4 key购买 nike

我已经阅读了很多关于将 std::cout 重定向到 stringstreams 的帖子,但是我在读取重定向的字符串时遇到了问题。

std::stringstream redirectStream;
std::cout.rdbuf( redirectStream.rdbuf() );

std::cout << "Hello1\n";
std::cout << "Hello2\n";

while(std::getline(redirectStream, str))
{
// This does not work - as the contents of redirectStream
// do not include the '\n' - I only see "Hello1Hello2"
}

我需要在初始输出中挑选出新行 - 谁能告诉我该怎么做?

谢谢。

最佳答案

对我来说很好:
注意:std::getline() 读取该行(但不是 '\n' 字符,行结束符在每行被读取后被丢弃)。但是每行都会进入一次循环。

#include <iostream>
#include <sstream>

int main()
{
std::stringstream redirectStream;
std::streambuf* oldbuf = std::cout.rdbuf( redirectStream.rdbuf() );

std::cout << "Hello1\n";
std::cout << "Hello2\n";

std::string str;
while(std::getline(redirectStream, str))
{
fprintf(stdout,"Line: %s\n",str.c_str());
// loop enter once for each line.
// Note: str does not include the '\n' character.
}

// In real life use RAII to do this. Simplified here for code clarity.
std::cout.rdbuf(oldbuf);
}

注意:您需要将旧的流缓冲区放回 std::cout 中。一旦 stringstream 'redirectStream' 超出范围,其缓冲区将被销毁,留下指向无效流缓冲区的 std::cout。由于 std::cout 的生命周期比“redirectStream”长,因此您需要确保 std::cout 不会访问无效对象。因此,最简单的解决方案是放回旧缓冲区。

关于c++ - 重定向 cout -> std::stringstream,没有看到 EOL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1881589/

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