cin>>我输入符号+时出错 [英] cin >> i error in input with symbol +

查看:174
本文介绍了cin>>我输入符号+时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C ++程序中,我正在尝试处理用户输入,该用户输入由点缀有运算符(+-/ *)的整数操作数组成。我非常乐于要求用户在每个运算符之前和之后放置空格。我的方法是假设不是int的任何东西都是运算符。因此,一旦流上出现非eof错误,我就会调用cin.clear()并将下一个值读入字符串。

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

此功能适用于/和*运算符,但不适用于+-运算符。原因是 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.

处理这种问题的C ++的好方法是什么?

What would be a good C++ way of dealing with this problem?

推荐答案

读取 std :: string s并使用 boost :: lexical_cast<> 或其等价物。

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






后记:如果您对Boost过敏,可以使用以下lexical_cast实现:


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

这篇关于cin&gt;&gt;我输入符号+时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆