3

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.

Anakhand
  • 2,838
  • 1
  • 22
  • 50

2 Answers2

2

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();
xskxzr
  • 12,442
  • 12
  • 37
  • 77
1

You can use istream::peek to check what the next character will be before extracting it. You can test the result of peek against your acceptable range, and if it matches, do the actual extraction.

BTW, if you want to skip whitespace, you'll also need to check for and handle that with peek() (by extracting and discarding whitespace characters). Even with skipws, peek() won't peek past the whitespace.

Sneftel
  • 40,271
  • 12
  • 71
  • 104