我的问题可以归结为,字符串从stringstream.str().c_str()内存中返回的字符串在哪里,为什么不能将其分配给const char*?
这个代码示例将比我更好地解释它
#include <string>
#include <sstream>
#include <iostream>
using namespace std;
int main()
{
stringstream ss("this is a string\n");
string str(ss.str());
const char* cstr1 = str.c_str();
const char* cstr2 = ss.str().c_str();
cout << cstr1 // Prints correctly
<< cstr2; // ERROR, prints out garbage
system("PAUSE");
return 0;
}
Run Code Online (Sandbox Code Playgroud)
stringstream.str().c_str()可以分配给a 的假设const char*导致我花了一段时间追踪的错误.
对于奖励积分,任何人都可以解释为什么替换cout声明
cout << cstr // Prints correctly
<< ss.str().c_str() // Prints correctly
<< cstr2; // Prints correctly (???)
Run Code Online (Sandbox Code Playgroud)
正确打印字符串? …