Re: null terminated buffer ?
SteveB schrieb:
If I have a buffer that I pass into sprintf does it need to be zero
terminated ?
No, sprintf does not make any assumptions concerning its
target (besides the fact that the user gave a sufficiently large
one). It will always write a final null character after formatting,
see 7.19.6.6 in C99.
char *buffer = new char[(sizeof(long)*8+1)];
May I ask, which reasoning leads to this unusual formula
to compute the expected max. target length? It looks
rather suspicious to me. If I correctly interpret your intend
to print any long number you should use something along of
2 + std::numeric_limits<long>::digits10.
Furtheron I recommend to use some self-administrating
class like boost::scoped_array<char>, std::vector<char> or
even std::string (with todays guarantees on its representation).
sprintf(buffer, "%d", 35L)
Two points:
(1) The provided argument does not match the formatting
specifier and thus causes undefined behaviour. The proper
format specifier for long is "%ld".
(2) If you need to use C formatting here and you have a
half-decent C/C++ library, you should use snprintf:
const int buflen = 2 + std::numeric_limits<long>::digits10;
boost::scoped_array<char> buffer(new char[buflen]);
snprintf(buffer.get(), buflen, "%ld", 35L);
std::string strnum(buffer)
Besides the missing semicolon this should work as
expected, using the smart ptr we have:
std::string strnum(buffer.get());
Since you end up with std::string anyway you should
definitively consider to use a stringstream:
std::ostringstream ss;
ss << 35L;
std::string strnum(ss.str());
delete[] buffer;
No reason for this if you have a self-administrating
class.
or should I add the '\0' to the buffer
manually as in:
char *buffer = new char[(sizeof(long)*8+1)];
sprintf(buffer, "%d\0", 35L)
No reason for this, because every string literal is
*always* a zero-terminated character sequence.
i was under the impression that the std::string constructor accepted
a char* as a paramter. is this wrong ?
There exists a std::string c'tor which accepts a const char*.
Why do you ask? Does your compiler not accept the code?
Greetings from Bremen,
Daniel Kr|gler
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]