Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getting cout output to a std::string

I have the following cout statement. I use char arrays because I have to pass to vsnprintf to convert variable argument list and store in Msg.

Is there any way we can get cout output to C++ std::string?

char Msg[100]; char appname1[100]; char appname2[100]; char appname3[100];   // I have some logic in function which some string is assigned to Msg. std::cout << Msg << " "<< appname1 <<":"<< appname2 << ":" << appname3 << " " << "!" << getpid() <<" " << "~" << pthread_self() << endl; 
like image 750
venkysmarty Avatar asked Mar 04 '11 11:03

venkysmarty


People also ask

Can you cout a string in C++?

You need to put it in a function. You need to #include <string> before you can use the string class and iostream before you use cout or endl . string , cout and endl live in the std namespace, so you can not access them without prefixing them with std:: unless you use the using directive to bring them into scope first.

How do you output a string?

using printf() If we want to do a string output in C stored in memory and we want to output it as it is, then we can use the printf() function. This function, like scanf() uses the access specifier %s to output strings. The complete syntax for this method is: printf("%s", char *s);

How do you display a string in C++?

In C++ you can do like that : #include <iostream> std::cout << YourString << std::endl; If you absolutely want to use printf, you can use the "c_str()" method that give a char* representation of your string.

Why is std :: cout not working?

There is no std::cout in C. In a windowing system, the std::cout may not be implemented because there are windows and the OS doesn't know which one of your windows to output to. never ever give cout NULL. it will stop to work.


1 Answers

You can replace cout by a stringstream.

std::stringstream buffer; buffer << "Text" << std::endl; 

You can access the string using buffer.str().

To use stringstream you need to use the following libraries:

#include <string>   #include <iostream>  #include <sstream>    
like image 89
Björn Pollex Avatar answered Sep 23 '22 20:09

Björn Pollex