【问题标题】:Store cout output into variable将 cout 输出存储到变量中
【发布时间】:2022-01-09 23:02:08
【问题描述】:

如何将 cout 的输出存储到字符串或字符类型的变量中?

我已经编写了以下代码,但它不起作用:

#include<iostream>
#include<stdio.h>
using namespace std; 

int main(){
    string n;
    n = (cout<<"\nHello world"); 
    cout<<n;    
    return 0;
}

【问题讨论】:

  • 为什么不先将字符串存储在n,然后再存储cout &lt;&lt; n
  • 您应该使用std::ostringstream 而不是std::cout

标签: c++ string cout


【解决方案1】:

当然有办法!但是你必须使用不同类型的流:

std::ostringstream ss;
ss << "\nHello world";
std::string result = ss.str();

另外,在 C++20 中,您可以简单地使用 std::format:

std::string n = std::format("Hello {}! I have {} cats\n", "world", 3);
// n == "Hello world! I have 3 cats\n"

【讨论】:

  • 在这种情况下,您应该使用std::ostringstream(仅输出)而不是std::stringstream(输入+输出),因为您不需要从流中读取输入。
  • 感谢您的知识。它的工作
  • @AlexG 很高兴!总是乐于提供帮助
【解决方案2】:

其他答案向您展示了如何直接使用 std::(o)stringstream 对象捕获格式化输出。但是,如果由于某种原因,您确实需要捕获std::cout 的输出,那么您可以暂时重定向std::cout 以使用std::ostringstream 的缓冲区,例如:

#include <iostream>
#include <sstream>
using namespace std; 

int main(){
    ostringstream oss;
    auto cout_buff = cout.rdbuf(oss.rdbuf());
    cout << "\nHello world";
    cout.rdbuf(cout_buff);
    string n = oss.str();
    cout << n;
    return 0;
}

Online Demo

【讨论】:

    【解决方案3】:
    #include <sstream>
    
    std::ostringstream a;
    a << "Hello, world!";
    std::string b = a.str(); // Or better, `std::move(a).str()`.
    
    std::cout << b;
    

    【讨论】:

    • 感谢它的工作,但在其中添加#include 库。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-27
    • 2023-02-13
    • 2011-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-10
    相关资源
    最近更新 更多