How to ignore white spaces input stream in operator overload >>

为君一笑 提交于 2019-12-25 02:11:50

问题


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

回答1:


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.

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




回答2:


I think I'd do something on this order:

stream.setf(std::skipws);

char open_bracket, close_bracket, colon;

unsigned num_items, temp_item;

stream >> open_bracket;
stream >> num_items;
stream >> colon;

for (int i=0; i<num_items; i++) {
    stream >> temp_item;
    temp_vec.push_back(temp_item);
}

stream >> close_bracket;

if (open_bracket != '[' || close_bracket != ']' || colon != ':')
    stream.setstate(ios::failbit); 

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.



来源:https://stackoverflow.com/questions/7959688/how-to-ignore-white-spaces-input-stream-in-operator-overload

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!