Search code examples
c++stringiostreamistream

Parsing integer from comma delimited string


I'm new to c++ and trying to find some example code to extract integers from comma delimited strings. I come across this code:

std::string str = "1,2,3,4,5,6";
std::vector<int> vect;

std::stringstream ss(str);

int i;

while (ss >> i)
{
    vect.push_back(i);

    if (ss.peek() == ',')
        ss.ignore();
}  

I have trouble understanding the while loop conditional statement: ss >> i. From my understanding, istream::>> returns the istream operated on. Error bits may be set by the operation. There doesn't seem to be a boolean variable involved. How can ss >> i serve as a conditional statement?

Additionally, does >> extract one or multiple characters? For example, if I have a string "13, 14". Does this operation return integers 1, 3, 1, 4 or integers 13, 14?

Thanks a lot, M


Solution

  • 1) Conditional statement.

    std::stringstream derives from std::ios, which defines:

    • In C++ 98 / C++ 03: operator void*() const

    Description: A null pointer if at least one of failbit or badbit is set. Some other value otherwise.

    • In C++ 11: explicit operator bool() const

    Description: true if none of failbit or badbit is set. false otherwise.

    That's why you can use this expression as condition for a loop - operator>> returns reference to stringstream object, which then is converted to either void* pointer or bool, depending on supported C++ version.

    More info about this: std::ios::operator bool

    2) operator>> applied for numbers extracts as many characters as it can:

    int main()
    {
        std::string str = "111,12,1063,134,10005,1226";
        std::vector<int> vect;
    
        std::stringstream ss(str);
    
        int i;
    
        while (ss >> i)
        {
            vect.push_back(i);
    
            if (ss.peek() == ',')
                ss.ignore();
        }
    
        return 0;
    }
    

    Content of vector: [111, 12, 1063, 134, 10005, 1226].

    Again, more info: std::istream::operator>>