我的问题可以归结为,从stringstream.str().c_str()
内存中返回的字符串在哪里,为什么不能分配给 a 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;
}
stringstream.str().c_str()
可以分配给 a的假设const char*
导致了我花了一段时间才找到的错误。
对于奖励积分,任何人都可以解释为什么cout
用
cout << cstr // Prints correctly
<< ss.str().c_str() // Prints correctly
<< cstr2; // Prints correctly (???)
正确打印字符串?
我在 Visual Studio 2008 中编译。