In a C++ program I’m trying to process user input which consists of integer operands interspersed with operators (+ – / *). I have the luxury of requiring users to put whitespace(s) before and after each operator. My approach is to assume that anything that’s not an int is an operator. So as soon as there’s a non eof error on the stream, I call cin.clear() and read the next value into a string.
#include <iostream>
#include <string>
//in some other .cpp i have these functions defined
void process_operand(int);
void process_operator(string);
using namespace std;
int main()
{
int oprnd;
string oprtr;
for (;; )
{
while ( cin >> oprnd)
process_operand(oprnd);
if (cin.eof())
break;
cin.clear();
cin >> oprtr;
process_operator(oprtr);
}
}
This works fine for / and * operators but not for + – operators. The reason is that operator>> eats away the + or – before reporting the error and doesn’t put it back on the stream. So I get an invalid token read into oprtr.
Ex: 5 1 * 2 4 6 * / works fine
5 1 + 2
^ ---> 2 becomes the oprnd here.
What would be a good C++ way of dealing with this problem?
Read in
std::strings and convert them usingboost::lexical_cast<>or its equivalent.Postscript: If you are allergic to Boost, you can use this implementation of lexical_cast: