我如何接受字符串或双精度输入? C ++

时间:2012-12-13 03:05:17

标签: c++ string function math double

好。所以我前段时间写了一个公式计算器,它有很多不同的功能。我今天打开它,注意到每次我访问某个功能然后完成该功能,程序就会回到主菜单。当然这很好,我编程就是为了做到这一点,但是当我访问计算器功能(简单的数学运算)时,我很生气,我完成了一个等式,我不能马上做另一个。我希望能够保持某个功能,直到我按下“q”,然后它将返回主菜单。

真正的问题是,我的函数只接受双精度数,所以如果我输入一个字符串('q'),程序就会崩溃。我需要一种方法让用户输入一个字符串一个双,这样我就可以检查它是否是'q'并且用户想要退出。

我想最终用我的所有函数做到这一点,但这里只是“calc”函数(最简单的函数):

    int calculation()
{
  double x=0, y=0, answer=0;
  char o;//operator variable
  cout<<"calculation: ";
  cin>>x>>o>>y; //I just don't know what to use here so that the user can enter a  
  cin.ignore(); //double or a string.
  if (o=='+') answer=x+y;
  else if (o=='-') answer=x-y;
  else if (o=='*') answer=x*y;
  else if (o=='/') answer=x/y;
  else if (o=='^') answer= pow(x, y);
  else if (o=='%') {
        answer= (100/x)*y; 
        cout<<"answer= "<<answer<<"%";
  }
  if (o!='%') cout<<"answer= "<<answer;
  cin.get();
  return 0;
}

我需要该功能不断重复,直到用户输入单个“q”。 抱歉所有的话。

1 个答案:

答案 0 :(得分:2)

分两步解决:

  1. 编写一个接受任何字符串的循环,只在输入'q'时退出。
  2. 将该字符串传递给新函数,该函数仅在字符串可以分解为两个操作数和运算符时执行计算(您可以使用stringstream)。
  3. 之后,您可以根据需要自定义功能。一种可能性是将运算符的字符串映射到采用两个操作数并打印结果的回调。然后,您可以将该映射传递给计算函数,以便您支持的运算符数量可以轻松增加。

    这是一个非常粗略的例子,只适用于添加,但演示了这个概念。

    #include <iostream>
    #include <cmath>
    #include <sstream>
    #include <map>
    using namespace std;
    
    typedef double (*p_fn)(double,double);
    
    double add(double x, double y)
    {
        return x + y;
    }
    
    typedef map<string,p_fn> operators;
    
    double execute( const operators &op, double x, double y, const string& o )
    {
        operators::const_iterator i = op.find(o);
        if( i != op.end())
        {
            p_fn f = i->second;
            double const result = f(x,y);
            return result;
        }
        cout<<"unknown operator\n";
        return 0;
    }
    
    bool get_data( double& x, double&y, string& o )
    {
        string s1,s2,s3;
        cin>>s1;
        if(s1=="q")
            return false;
        cin>>s2>>s3;
        stringstream sstr;
        sstr<<s1<<" "<<s2<<" "<<s3;
        sstr>>x>>o>>y;
        stringstream sstr2;
        sstr2<<x<<" "<<o<<" "<<y;
        return sstr.str() == sstr2.str();
    }
    
    double calculation2( const operators& op )
    {
        double x,y;
        string o;
        while(get_data(x,y,o))
            cout<<execute(op, x, y, o)<<"\n";
        return 0;
    }
    
    int main(int argc, char* argv[])
    {
        operators o;
        o["+"]=add;
        calculation2(o);
        return 0;
    }
    

    此示例使用函数指针将字符串“+”映射到函数add(x,y)。它还使用字符串流来执行非常基本的输入验证。

相关问题