Search code examples
c++istringstream

Extraction operator into non-numeric character


Given an istringstream, is it possible to "extract" its contents into a character only if the character to be extracted is non-numeric (i.e. not 0-9)?

For example, this

string foo = "+ 2 3";
istringstream iss(foo);

char c;
iss >> skipws >> c;  //Do this only if c would be non-numeric

should extract '+', but if foo were "2 + 3", it shouldn't extract anything, since the first [non-whitespace] character is '2', which is numeric.

To give some context, I need this to make a recursive "normal polish notation" (i.e. prefix notation) parser.


Solution

  • You can use unget to put back the character if it is numeric.

    string foo = "+ 2 3";
    istringstream iss(foo);
    
    char c;
    iss >> skipws >> c;
    if (std::isdigit(c)) iss.unget();