我想用空格分隔流中的大量输入。
我知道我可以使用 std::ostream_iterator
的定界符构造函数,但并非我所有的输入都是同一类型。
有没有一种方法可以告诉流默认使用分隔符?
std::ostringstream foo;
foo << 1 << 1.2 << "bar" // I want this to print "1 1.2 bar "
最佳答案
您可以像下面这样包装流,(只是一个基本想法)
struct mystream
{
mystream (std::ostream& os) : os(os) {}
std::ostream& os;
};
template <class T>
mystream& operator<< (mystream& con, const T& x)
{
con.os << x << " "; // add extra delimeter
return con;
}
int main()
{
std::ostringstream foo;
mystream c(foo) ; // mystream c( std::cout ) ;
c << 1 << 1.2 << "bar" ;
}
参见 here
关于c++ - 我可以设置 ostream 分隔符吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24529879/