【发布时间】:2010-11-25 08:36:35
【问题描述】:
我的问题可以归结为,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;
}
stringstream.str().c_str() 可以分配给const char* 的假设导致了一个我花了一段时间才找到的错误。
对于加分,谁能解释为什么用
替换cout语句
cout << cstr // Prints correctly
<< ss.str().c_str() // Prints correctly
<< cstr2; // Prints correctly (???)
正确打印字符串?
我在 Visual Studio 2008 中编译。
【问题讨论】:
标签: c++ string memory stringstream