Take the 2-minute tour ×

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)
        if (cin.eof())
        cin >> 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?

share|improve this question

3 Answers 3

up vote 5 down vote accepted

Read in std::strings and convert them using boost::lexical_cast<> or its equivalent.

int main()
    string token;
    while ( cin >> token) {
        try {
        } catch (std::bad_cast& e) {

Postscript: If you are allergic to Boost, you can use this implementation of lexical_cast:

template <class T, class U>
T lexical_cast(const U& u) {
  T t;
  std::stringstream s;
  s << u;
  s >> t;
  if( !s )
    throw std::bad_cast();
  if( s.get() != std::stringstream::traits_type::eof() )
    throw std::bad_cast();
  return t;
share|improve this answer

I think >> thinks you are starting another integer with +/-. Then gets mad when you don't follow with digits.

As @Robᵩ said, read a string and cast. I would only offer another choice from the standard library:

int stoi(const string& str, size_t *idx = 0, int base = 10);

This throws invalid_argument if no conversion could be performed or out_of_range if the converted value is outside the range of representable values for the return type.

This is from The Standard.

share|improve this answer
+1 Excellent recommendation. Yet another C++11 feature that I need to add to my bag of tricks. See also en.cppreference.com/w/cpp/string/basic_string/stol –  Robᵩ May 15 '12 at 15:38

Don't know about C++ way, but C-like way would be to read in strings and use atoi to convert to integers.

share|improve this answer
But C is an entirely different language. This answer adds nothing, -1. –  delnan May 14 '12 at 15:53
atoi is available in C++ and is easier to use that boost. In fact, stoi idea above is very similar (but won't work with older compiler). In any case, the important thing is to read in strings rather than ints. –  Arkadiy May 14 '12 at 18:14

Your Answer


