Home > Back-end >  Store cout output into variable
Store cout output into variable

Time:12-04

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;
}

CodePudding user response:

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

std::cout << b;

CodePudding user response:

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

std::stringstream 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"
  • Related