如何在运算符重载中忽略空格输入流 >> [英] How to ignore white spaces input stream in operator overload >>

查看:74
本文介绍了如何在运算符重载中忽略空格输入流 >>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前我重载的 operator>> 函数接受输入 [4: 1 2 3 4 ] 并且工作正常.但是如何忽略任意数量的空格,以便它可以接受 [ 4 : 1 2 3 4 ] ,即输入前的任意数量的空格?

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;
}

推荐答案

stream >> std::ws;

从输入序列的当前位置提取尽可能多的空白字符.一旦发现非空白字符,提取就会停止.提取的这些空白字符不存储在任何变量中.

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.

请注意,即使 skipws 标志之前在源流中是 unsetf,这也会跳过空格,因此您无论如何都应该这样做.

Note that this will skip whitespace even if the skipws flag was previously unsetf in the source stream, so you should do it anyways.

这篇关于如何在运算符重载中忽略空格输入流 &gt;&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆