2

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 .

JoeG
  • 12,994
  • 1
  • 38
  • 63
rajat
  • 3,415
  • 15
  • 56
  • 90

2 Answers2

8

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*'. */
hmjd
  • 120,187
  • 20
  • 207
  • 252
  • Sry this , does not work well . It gives me a trailing question mark at the end of the filename . what it causing this problem . – rajat Sep 12 '12 at 16:15
  • @rajat, assuming `argv[1]` is populated the code is correct. See http://ideone.com/alBG9 for demo. – hmjd Sep 12 '12 at 16:22
  • it can't depend on how argv[1] is populated because i am getting question mark at the end of the file name not in between as i am embedding .txt like this sstm< – rajat Sep 12 '12 at 16:28
  • could you please try and see if you are getting the same problem if you write a file . – rajat Sep 12 '12 at 16:29
3

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.

Community
  • 1
  • 1
Brent Arias
  • 29,277
  • 40
  • 133
  • 234