std::string str(char_buff);
printf("%s\n", str); // prints random nonsense
The problem is that %s
makes printf()
expect a const char*
; in other words, %s
is a placeholder for const char*
.
Instead, you passed str
, which is an instance of std::string
, not a const char*
.
To fix that, just use the c_str()
method of std::string
:
printf("%s\n", str.c_str());
c_str()
returns a C-style pointer to a NUL
-terminated string, as expected from C functions like printf()
.
As a side note:
char char_buff[40];
sprintf_s(char_buff, 40, "test" );
Note that sprintf_s()
can be used in a simpler form, making it to automatically deduce the destination buffer length, thanks to some template "magic":
sprintf_s(char_buff, "test"); // char_buff size automatically deduced
See this sprintf_s()
template from MSDN documentation:
template <size_t size>
int sprintf_s(
char (&buffer)[size],
const char *format [,
argument] ...
); // C++ only