Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ stringstream concatenate query

Tags:

c++

string

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 .

like image 535
rajat Avatar asked Mar 01 '26 13:03

rajat


2 Answers

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*'. */
like image 195
hmjd Avatar answered Mar 04 '26 02:03

hmjd


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.

like image 25
Brent Arias Avatar answered Mar 04 '26 03:03

Brent Arias



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!