谁能告诉我一些在c++中使用字符串流的实际例子,即使用流插入和流提取操作符输入和输出到字符串流?
发布于 2010-02-25 22:47:37
您可以使用字符串流将任何实现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-25 23:53:18
在创建消息时,我主要使用它们作为内存缓冲区:
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();
}它很有用,因为它为使用字符缓冲区带来了std::stream的所有可扩展性(ostreams可扩展性和区域设置支持,缓冲区内存管理被隐藏,等等)。
我见过的另一个例子是gsoap库中的错误报告,使用依赖注入:soap_stream_fault接受一个ostream&参数来报告错误消息。
如果你愿意,你可以传递std::cerr,std::cout或者std::ostringstream实现(我将它与std::ostringstream实现一起使用)。
发布于 2010-02-25 22:52:41
除了优点之外,如果你使用的是gcc 4.3.1,还有one point to carefully consider。我没有看过之前的版本的《gcc》。
https://stackoverflow.com/questions/2334735
复制相似问题