AlexG
AlexG

Reputation: 77

Store cout output into variable

How can I store the output from cout into a variable of string or character type?

I have written following code but it doesn't work:

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

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

Upvotes: 1

Views: 4439

Answers (3)

Guillaume Racicot
Guillaume Racicot

Reputation: 41750

Of course there's a way! But you have to use a different kind of stream:

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

Also, in C++20, you can simply use std::format:

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

Upvotes: 0

Remy Lebeau
Remy Lebeau

Reputation: 595497

Other answers have shown you how to capture formatted output using a std::(o)stringstream object directly. But, if for some reason, you really need to capture the output of std::cout, then you can temporarily redirect std::cout to use a std::ostringstream's buffer, eg:

#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

Upvotes: 1

HolyBlackCat
HolyBlackCat

Reputation: 96042

#include <sstream>
std::ostringstream a;
a << "Hello, world!";
std::string b = a.str(); // Or better, `std::move(a).str()`.

std::cout << b;

Upvotes: 1

Related Questions