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;
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.
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);
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.
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With