C ++で文字列ストリームを使用する実際の例、つまり、ストリーム挿入およびストリーム抽出演算子を使用した文字列ストリームへの入力と出力について教えてもらえますか?
6347 次
4 に答える
11
文字列ストリームを使用して、実装するものをすべて文字列に変換できoperator <<
ます。
#include <sstream>
template<typename T>
std::string toString(const T& t)
{
std::ostringstream stream;
stream << t;
return stream.str();
}
あるいは
template <typename U, typename T>
U convert(const T& t)
{
std::stringstream stream;
stream << t;
U u;
stream >> u;
return u;
}
于 2010-02-25T14:47:36.773 に答える
3
私はメッセージを作成する際に、主にメモリバッファとしてそれらを使用します。
if(someVector.size() > MAX_SIZE)
{
ostringstream buffer;
buffer << "Vector should not have " << someVector.size() << " eleements";
throw std::runtime_error(buffer.str());
}
または複雑な文字列を作成するには:
std::string MyObject::GenerateDumpPath()
{
using namespace std;
std::ostringstream dumpPath;
// add the file name
dumpPath << "\\myobject."
<< setw(3) << setfill('0') << uniqueFileId
<< "." << boost::lexical_cast<std::string>(state)
<< "_" << ymd.year
<< "." << setw(2) << setfill('0') << ymd.month.as_number()
<< "." << ymd.day.as_number()
<< "_" << time.hours()
<< "." << time.minutes()
<< "." << time.seconds()
<< ".xml";
return dumpPath.str();
}
sのすべての拡張性を文字バッファの使用にもたらすので便利ですstd::stream
(ostreamの拡張性とロケールのサポート、バッファメモリ管理は非表示など)。
私が見たもう1つの例は、依存性注入を使用したgsoapライブラリでのエラー報告です。soap_stream_faultはostream&パラメーターを使用してエラーメッセージを報告します。
必要に応じて、std :: cerr、std :: cout、またはstd :: ostringstream実装を渡すことができます(私はstd :: ostringstream実装で使用します)。
于 2010-02-25T15:53:18.123 に答える
2
通常のストリームを使用できる場所であればどこでも使用できます。
したがって、ファイルから読み取っている状況では、文字列ストリームから読み取る可能性があります。
void compile(std::istream& str)
{
CPlusPlusLexer lexer(str);
CPlusPlusParser parser(lexer);
BackEnd backend(parser);
backend.compile();
}
int main()
{
std::fstream file("Plop.cpp");
compile(file);
std::stringstream test("#include <iostream>\n int main() { std::cout << \"H World\n\";}");
compile(test);
}
于 2010-02-25T14:57:42.073 に答える
2
利点に加えて、gcc4.3.1を使用する場合は慎重に検討する必要がある1つのポイントがあります。以前のバージョンのgccはチェックしていません。
于 2010-02-25T14:52:41.457 に答える