rajat
rajat

Reputation: 3553

C++ stringstream concatenate query

The code is supposed to concatenate argv[1] with .txt , and with _r.txt .

std::stringstream sstm;
std::stringstream sstm_r;

sstm<<argv[1]<<".txt";
sstm_r<<argv[1]<<"_r.txt";

const char* result = sstm.str().c_str();
const char* result_r = sstm_r.str().c_str();

fs.open(result);
fs_r.open(result_r);

cout<<result<<endl;
cout<<result_r<<endl;

But what it does is , when i enter "abc" as argv[1] , it gives me , result as "abc_r.tx0" and result_r also same "abc_r.tx0" .What is the correct way to do this and why is this wrong .

Upvotes: 2

Views: 1128

Answers (2)

Brent Arias
Brent Arias

Reputation: 30165

Work with the strings like this:

{
  const std::string& tmp = stringstream.str();
  const char* cstr = tmp.c_str();
}

This is taken from another exchange here.

Upvotes: 3

hmjd
hmjd

Reputation: 121971

The std::string instances to which the pointers returned by c_str() are associated will be destroyed leaving result and result_r as dangling pointers, resulting in undefined behaviour. You need to save the std::string instances if you want to use c_str():

const std::string result(sstm.str());

fs.open(result.c_str());  /* If this is an fstream from C++11 you
                             can pass a 'std::string' instead of a
                             'const char*'. */

Upvotes: 8

Related Questions