如何在运算符重载中忽略空格输入流>>
目前,我的重载 operator>>
函数接受输入 [4: 1 2 3 4 ]
并且工作正常。但是我怎样才能忽略任意数量的空格,以便它可以接受 [ 4 : 1 2 3 4 ]
,即输入之前的任意数量的空格?
istream& operator>>( istream & stream, my_vector & vector_a ) {
string token2;
int vec_size;
vector<double> temp_vec;
bool push = false;
while (stream >> token2) {
if (token2[0] == '[' && token2[2] ==':') {
push = true;
}
if (token2 == "]") {
break;
}
else if(!(token2[0] == '[' && token2[2] ==':')) {
stream.setstate(ios::badbit);
}
if(push) {
istringstream str(token2);
double v;
if (str >> v)
temp_vec.push_back(v);
vector_a.set_data(temp_vec);
}
}
return stream;
}
Currently my overloaded operator>>
function takes the input [4: 1 2 3 4 ]
and works fine. But how can I ignore any number of white spaces so that it can accept [ 4 : 1 2 3 4 ]
, i.e any number of white spaces before the input?
istream& operator>>( istream & stream, my_vector & vector_a ) {
string token2;
int vec_size;
vector<double> temp_vec;
bool push = false;
while (stream >> token2) {
if (token2[0] == '[' && token2[2] ==':') {
push = true;
}
if (token2 == "]") {
break;
}
else if(!(token2[0] == '[' && token2[2] ==':')) {
stream.setstate(ios::badbit);
}
if(push) {
istringstream str(token2);
double v;
if (str >> v)
temp_vec.push_back(v);
vector_a.set_data(temp_vec);
}
}
return stream;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
从输入序列中的当前位置提取尽可能多的空白字符。一旦发现非空白字符,提取就会停止。提取的这些空白字符不存储在任何变量中。
请注意,即使
skipws
标志先前已在源流中unsetf
,这也会跳过空格,因此您无论如何都应该这样做。Extracts as many whitespace characters as possible from the current position in the input sequence. The extraction stops as soon as a non-whitespace character is found. These whitespace characters extracted are not stored in any variable.
Note that this will skip whitespace even if the
skipws
flag was previouslyunsetf
in the source stream, so you should do it anyways.我想我会按照这个顺序做一些事情:
请注意,为失败的转换设置的位是failbit,而不是badbit。 badbit 适用于尝试从磁盘读取失败之类的情况。
I think I'd do something on this order:
Note that the bit to set for a failed conversion is failbit, not badbit. badbit is intended for things like a failed attempt at reading from the disk.