Search code examples
c++iostreamistream

Istream consume at most N whitespace characters


Is it possible to tell a std::istream to only consume a fixed number (namely, 1) of whitespace characters when applying the operator>>? I have a string I'd like to parse into parameters, but some of the parameters are empty, which is causing subsequent calls to operator>> to fail.


Solution

  • Try std::noskipws :

    std::cin >> std::noskipws;
    char ws;
    std::string firstField, secondField, thirdField;
    std::cin >> firstField >> ws >> secondField >> ws >> thirdField;
    

    Or, you could slurp the entire line into a string (see std::getline), and then split it with Boost.