如何只接受cin输入中的数字?

时间:2017-09-11 01:01:13

标签: c++ if-statement calculator

我正在制作一个非常简单的计算器(只有两个数字可以加,减,乘或分)c ++程序,除了一行代码,我差不多完成了。我想让我的程序显示错误信息,如果输入除了数字之外的任何东西......但我没有线索如何。另外请记住,我是c ++的初学者,我不想使用太疯狂的东西。我尝试用多种不同的方式打字询问这个问题,但一无所获。如果有一个类似的问题,请告诉我,我会把它拿下来。有问题的行被注释掉了,它是main()的第6行。在此先感谢任何帮助:)))这是代码:

    #include <iostream>
    #include <string>
    #include <cmath>
    #include <iomanip>
    using namespace std;

    string calcSign;
    double result;
double cAdd(double num1, double num2);
double cSubtract(double num1, double num2);
double cMultiply(double num1, double num2);
double cDivide(double num1, double num2);


int main()
{
   double firstNumber, secondNumber;
    cout << "Hello! Please enter first number: " << endl;
    cin >> firstNumber;

    /*
    if (firstNumber != ){
        cout << "**ERROR...Please enter a valid number";
    }
     */

    cout << "+, -, *, or / ?";
    cin >> calcSign;

    cout << "What is the second number?: ";
    cin >> secondNumber;

    // If/else logic to determine what math operation to use
    if (calcSign == "+") {
        result = cAdd(firstNumber, secondNumber);
        cout << setprecision(2) << fixed << endl;
        cout << firstNumber << " " << calcSign << " " << secondNumber << " = " << result << endl;
    }
    else if (calcSign == "-") {
        result = cSubtract (firstNumber, secondNumber);
        cout << setprecision(2) << fixed << endl;
        cout << firstNumber << " " << calcSign << " " << secondNumber << " = " << result << endl;
    }
    else if (calcSign == "*") {
        result = cMultiply(firstNumber, secondNumber);
        cout << setprecision(2) << fixed << endl;
        cout << firstNumber << " " << calcSign << " " << secondNumber << " = " << result << endl;
    }
    else if (calcSign == "/") {
        result = cDivide(firstNumber, secondNumber);
        cout << setprecision(2) << fixed << endl;
        cout << firstNumber << " " << calcSign << " " << secondNumber << " = " << result << endl;
    }
    else if (calcSign != "+" || calcSign != "-" || calcSign != "*" || calcSign != "/") {
        cout << " ** Error - Please Enter a Valid Sign" << endl;
    }
    return 0;
}

// Two numbers multiplication constructor function
double cAdd(double num1, double num2) {
    double result1 = (num1 + num2);
    return result1;
}

double cSubtract(double num1, double num2) {
    double result1 = (num1 - num2);
    return result1;
}

double cMultiply(double num1, double num2) {
    double result1 = (num1 * num2);
    return result1;
}

double cDivide(double num1, double num2) {
    double result1 = (num1 / num2);
    return result1;
}

0 个答案:

没有答案