私の質問は要約すると、メモリ内のライブから返された文字列はどこにあり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 (???)
文字列を正しく印刷しますか?
VisualStudio2008でコンパイルしています。