2

I know how to do it with cout:

cout << "string" << 'c' << 33;

But how to perform this so output is redirected to variable instead directly to standard out ?

const char* string << "string" << 'c' << 33; //doesn't work
0

2 Answers 2

10

Use std::stringstream from C++ standard library.

It works like the following:

std::stringstream ss;
ss << "string" << 'c' << 33;
std::string str = ss.str();
const char* str_ansi_c = str.c_str();

Keep in mind str still needs to be in the scope while you are using C-style str_ansi_c.

Sign up to request clarification or add additional context in comments.

3 Comments

stringstream isn't a part of the STL.
@Pubby: No, it's part of the C++ standard library. A minor point of pedantry. But computers are nothing if not pedantic.
Should it not be const char* str_ansi_c = str.c_str();?
2
#include <sstream>
#include <iostream>

main()
{
  std::stringstream ss;
  ss << "string" << 'c' << 33;

  std::string str = ss.str();
  std::cout << str;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.