どのように私はC ++でにstringstreamから文字列に変換しますか?
-
20-08-2019 - |
質問
どのように私はC ++でstd::stringstream
するstd::string
から変換するのですか?
私は、文字列ストリーム上のメソッドを呼び出す必要がありますか?
解決
yourStringStream.str()
他のヒント
基本となる文字列オブジェクトの内容を管理します。
1)
rdbuf()->str()
呼び出すことであるかのように基本となる文字列のコピーを返します。2)
呼び出したように基本となる文字列の内容を置き換えますrdbuf()->str(new_str)
...のメモの
strで返された基本的な文字列のコピーはとても直接のhref = "http://en.cppreference.com/w/cpp/string <呼び出して、式の最後に破壊される一時的なオブジェクトであります/のbasic_string / c_str」REL = "noreferrer">
c_str()
のstr()
の結果にダングリングポインタをもたらす(auto *ptr = out.str().c_str();
で例えば)...
std::stringstream::str()
あなたが探している方法である。
std::stringstream
で
template <class T>
std::string YourClass::NumericToString(const T & NumericValue)
{
std::stringstream ss;
ss << NumericValue;
return ss.str();
}
std::ostringstream
より汎用的なツールです。あなたは、この特定のジョブのために、より特化したクラスstd::wstring
を使用することができます。
template <class T>
std::string YourClass::NumericToString(const T & NumericValue)
{
std::ostringstream oss;
oss << NumericValue;
return oss.str();
}
あなたは、文字列のstd::wstringstream
タイプで作業している場合は、、あなたの代わりにstd::wostringstream
好むNumericValue
または必要があります。
template <class T>
std::wstring YourClass::NumericToString(const T & NumericValue)
{
std::wostringstream woss;
woss << NumericValue;
return woss.str();
}
あなたは、文字列の文字型は、実行時することができ、選択したい場合は、、あなたもそのテンプレート変数にする必要があります。
template <class CharType, class NumType>
std::basic_string<CharType> YourClass::NumericToString(const NumType & NumericValue)
{
std::basic_ostringstream<CharType> oss;
oss << NumericValue;
return oss.str();
}
上記の全ての方法については、次の2つのヘッダファイルが含まれている必要があります。
#include <string>
#include <sstream>
上記の例では、引数がstd::string
も<=>として渡すことができ、または<=>それぞれ<=>と<=>インスタンスで使用することに留意されたいです。 <=>が数値である必要はない。
は、メモリから、あなたがのstd ::文字列値を取得するにstringstream :: strの()を呼び出します。
私は()メソッドを呼び出すの.str前に「\ 0」でstrstreamのバッファを終了しなければならないことを追加したいと思います。文字列をダンプするときそうしないと、不正な文字を取得します。