C++ でからstd::stringstream
に変換するにはどうすればよいですか?std::string
文字列ストリームでメソッドを呼び出す必要がありますか?
C++ でからstd::stringstream
に変換するにはどうすればよいですか?std::string
文字列ストリームでメソッドを呼び出す必要がありますか?
</p>
yourStringStream.str()
.str() メソッドを使用します。
基になる文字列オブジェクトの内容を管理します。
1) を呼び出したかのように、基になる文字列のコピーを返します
rdbuf()->str()
。
rdbuf()->str(new_str)
2) ...を呼び出すかのように、基になる文字列の内容を置き換えます。ノート
str によって返される基になる文字列のコピーは、式の最後で破棄される一時オブジェクトである
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::stringstream
はより一般的なツールです。std::ostringstream
この特定のジョブには、より特化したクラスを使用できます。
template <class T>
std::string YourClass::NumericToString(const T & NumericValue)
{
std::ostringstream oss;
oss << NumericValue;
return oss.str();
}
std::wstring
文字列のタイプを使用している場合は、代わりにstd::wstringstream
orを使用する必要がありますstd::wostringstream
。
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>
上記の例の引数NumericValue
は、 として渡すことも、std::string
およびインスタンスとstd::wstring
一緒に使用することもできます。が数値である必要はありません。std::ostringstream
std::wostringstream
NumericValue
メモリから、呼び出して値stringstream::str()
を取得しstd::string
ます。