Re: does std::string have something like CString::GetBuffer?
* sas:
with string i have to do this:
int a = 5;
std::string str;
char buffer[MAX_PATH];
strcpy(buffer, str.c_str());
sprintf(buffer, "var = %d", a);
str = buffer;
i have to use an additional buffer for std::string
No, you don't.
All you have achieved is some obfuscation and unsafety.
With std::string you can use resize() to allocate a suitably large buffer, and
&s[0] to get a pointer to the internal buffer.
#include <iostream> // std::cout
#include <ostream> // std::endl, operator<<
#include <string> // std::string
#include <cstdio> // std::sprintf
int main()
{
int a = 5;
std::string s;
s.resize( 40 );
s.resize( sprintf( &s[0], "var = %d", a ) );
std::cout << s << std::endl;
}
Of course in this particular case (just an example) you should better use a
std::ostringstream,
#include <iostream> // std::cout
#include <ostream> // std::endl, operator<<
#include <string> // std::string
#include <sstream> // std::ostringstream
int main()
{
int a = 5;
std::ostringstream s;
s << "var = " << a;
std::cout << s.str() << std::endl;
}
or even better (for this particular case) use boost::dynamic_cast, which
internally does the ostringstream thing for you,
#include <iostream> // std::cout
#include <ostream> // std::endl, operator<<
#include <string> // std::string
#include <boost/lexical_cast.hpp> // boost::lexical_cast
int main()
{
using namespace std;
using namespace boost;
int a = 5;
string s = "var = " + lexical_cast<string>( a );
cout << s << endl;
}
Cheers, & hth,
- Alf
PS: Add 'const' as appropriate.
--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?