sprintf中char数组与std::string的输出差异原因咨询
std::string Causes Garbage Output with sprintf Great question! This issue boils down to how sprintf expects input, and the core differences between C-style char arrays and C++ std::string objects. Let's break it down clearly:
1. What sprintf needs for %s
The %s format specifier in sprintf requires a const char*—a pointer to the start of a null-terminated C-style string. It reads bytes from that memory address until it hits a \0 character to build the output.
2. Why char arrays work perfectly
When you use char str1[] = "ahoy";, str1 is a plain character array. In C/C++, passing an array to a function automatically "decays" it into a pointer to its first element. So when you pass str1 to sprintf, it gets implicitly converted to const char*—exactly what %s expects. sprintf can then read the characters from the array until it hits the trailing \0, producing the correct output.
3. Why std::string spits out garbage
A std::string is a C++ class object, not a raw array. Its internal structure includes more than just the string characters: it typically holds a pointer to the actual character data, the string's length, and allocated capacity.
When you pass the std::string object directly to sprintf, the compiler doesn't automatically convert it to const char*. Instead, it treats the memory of the std::string object itself as if it were a const char* pointer. This means sprintf tries to read characters from a random, invalid memory address (the value of whatever member sits first in the std::string structure), leading to the garbage output you see.
The Simple Fix
To get a valid const char* from a std::string, use the c_str() method (or data() in C++11 and later—they work the same for this use case):
sprintf(buf, "%s %s\n", str1.c_str(), str2.c_str());
Bonus: Safer C++-Style Alternative
Since you're working in C++, it's cleaner and safer to skip sprintf entirely. std::cout natively understands std::string objects, so you can write:
std::cout << str1 << " " << str2 << "\n";
This also avoids the risk of buffer overflow (if your combined string was longer than 50 characters, buf would overflow and cause undefined behavior).
内容的提问来源于stack exchange,提问作者Joe

