我可以设置ostream分隔符吗?
Can I Set an ostream Delimiter
我想用空格分隔流中的许多输入。
我知道我可以使用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" ;
}
看到
您可以使用流缓冲区和虚函数将此功能捆绑到流中。例如:
class space_delimited_output_buffer : public std::streambuf
{
public:
space_delimited_output_buffer(std::streambuf* sbuf)
: m_sbuf(sbuf)
{ }
virtual int_type overflow(int_type c)
{
return m_sbuf->sputc(c);
}
virtual int sync()
{
if (ok_to_write)
this->sputc(' ');
else
ok_to_write = true;
return internal_sync();
}
private:
std::streambuf* m_sbuf;
bool ok_to_write = false;
int internal_sync()
{
return m_sbuf->pubsync();
}
};
class space_delimited_output_stream
: public std::ostream
, private virtual space_delimited_output_buffer
{
public:
space_delimited_output_stream(std::ostream& os)
: std::ostream(this)
, space_delimited_output_buffer(os.rdbuf())
{
this->tie(this);
}
};
int main() {
space_delimited_output_stream os(std::cout);
os << "abc" << 123 << "xyz";
}
现场演示
相关文章:
- ostream过载时的缓冲区冲洗
- 需要从 istream 和 ostream 派生 iostream
- 当用户键入分隔符时,停止getline()输入
- 为什么在逗号分隔符上下文中将预增量的结果强制转换为void
- "ostream &os"有什么用?
- 如何在 c++ 中使用 ',' 作为 getline 分隔符
- 为什么常量词在重载运算符中不与 ostream 对象一起使用<<?
- 带有多个字符分隔符的正则表达式
- 使用 char 分隔符解析C++中的字符串,但将可重复的字符保留为每个解析的子字符串 (C++ STL) 中的分隔符
- 字符串开头的分隔符
- 尝试将 c 字符串数组与分隔符连接起来
- 我的运算符重载是否有效<<(流插入)左操作数不是 ostream
- 正则表达式以匹配数字的重复模式,后跟任何类型的分隔符?
- C++表达SFINAE和ostream操纵器
- 根据新的行分隔符从字符串中删除子字符串
- 在抛出 'std::runtime_error' 的实例后终止调用 what(): Filebuf 和 ostream 的 I/O 错误
- 同一分隔符之间的多个子字符串
- 通过分隔符分隔包含 UTF-16 BE 文本的uint8_t数组
- 我可以设置ostream分隔符吗?
- 为什么使用 ostream 运算符<<打印字符串时空格不充当分隔符?