首页 > 解决方案 > When parsing a space delimitated string, is there any advantage using getline over stringstream::operator>>?

问题描述

int main()
{
    std::string s = "my name is joe";
    std::stringstream ss{s};
    std::string temp;
    while(std::getline(ss, temp, ' '))
    {
        cout << temp.size() << " " << temp << endl;
    }

    //----------------------------//

    ss = std::stringstream{s};
    while(ss >> temp)
    {
        cout << temp.size() << " " << temp << endl;
    }

}

I've always used the former, but I'm wondering if there's any advantage to using the latter? I've typically always used the former because I feel that if someone were to instead change the string to a comma delimitated string, then all I need to do is put in a new delimiter, whereas the operator>> would read in the commas. But for space delimitation, it seems there is no difference.

标签: c++parsingoperatorsgetlinestringstream

解决方案


std::getline() and operator>> are intended for different purposes. It is not a matter of which one is more advantageous than the other. Use the one that is better suited for the task at hand.

operator>> is for formatted input. It reads in and parses many different data types, including strings. If there is no error state on the input stream, it skips leading whitespace (unless the skipws flag on the input stream is disabled, such as with the std::noskipws manipulator), and then it reads and parses characters until it encounters whitespace, a character that does not belong to the data type being parsed, or the end of the stream.

std::getline() is for unformatted input of strings only. If there is no error state on the input stream, it does not skip leading whitespace, and then it reads characters until it encounters the specified delimiter (or '\n' if not specified), or the end of the stream.


推荐阅读