Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::to_string store in const char*

Tags:

c++

string

I need to convert number to string and store it into a const char* but problem is that const char* variable is blank after assignment.

In the following example code I expect to see number output converted to const char*

#include <iostream>
#include <string>

int main()
{
    int number = 123;
    const char* ptr_num_string = std::to_string(number).c_str();
    std::cout << "number to string is: " <<  ptr_num_string << std::endl;
    std::cin.get();
    return 0;
}

Output is blank:

number to string is:

How do I convert number into a const char* ?


1 Answers

  • std::to_string returns a temporary std::string.
  • The pointer returned by std::string::c_str is invalidated by any non-const operation on the string itself - this is because it basically gives you a pointer to the string's internal buffer.
  • Destroying a std::string is definitely a non-const operation!

Therefore, you can't expect to take a pointer into the string returned by to_string and ever be able to use that. You need to save a copy of that string in the first place:

int number = 123;
std::string const numAsString = std::to_string(number);
char const* ptrToNumString = numAsString.c_str(); // use this as long as numAsString is alive

What you are doing is called Undefined Behaviour - this means that your program is invalid, and anything could happen. It could crash, it could print out some garbage, it could appear to work normally, it could do a different one of these each time you run your program...

like image 116
BoBTFish Avatar answered Feb 12 '26 16:02

BoBTFish



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!