I try to convert a unsigned long into a character string, appending a comma at the end of the it. When compiling and running the test code you can find below, I get the following output:
"1234," "1234"
"1234"
The test code is:
#include <cstdio>
#include <iostream>
int main () {
unsigned long c = 1234;
char ch[50];
char ch1[50];
sprintf(ch, "%lu,", c);
std::cout << "\"" << ch << "\"" << " \"" << c << "\"" << std::endl;
snprintf(ch1, 5, "%s", ch);
std::cout << "\"" << ch1 << "\"" << std::endl;
return 1;
}
As far as I understand, ch should be of length 5, 4 digits plus 1 for the comma.
Do I miss an extra plus one for the termination character?
Cheers!
The size that is passed to
snprintfincludes the terminating null character. Although it is not printed, it still takes space in the buffer.You should pass
strlen(ch) + 1instead. Or even better, justsizeof(ch1)will suffice since you want to accommodate the entire result before filling the buffer.Also make sure that the destination buffer is always of a sufficient size, equal to or greater than the size you pass to
snprintf. In your particular case it can hardly happen, but in general you should keep that in mind.