cin >> i error in input with symbol +

不打扰是莪最后的温柔 提交于 2019-12-12 22:21:32

问题


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?


回答1:


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

int main()
{
    string token;
    while ( cin >> token) {
        try {
            process_operand(boost::lexical_cast<int>(token));
        } catch (std::bad_cast& e) {
            process_operator(token);
        }
    }
}

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;
}



回答2:


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.



来源:https://stackoverflow.com/questions/10586720/cin-i-error-in-input-with-symbol

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!