C ++新手 - 基本计算器问题

时间:2012-08-17 16:24:14

标签: c++

我正在尝试学习一些C ++,我决定构建一个基本的I / O计算器。它正确运行,直到第二个getUserInput(),然后它自动输入0并终止。我无法弄清楚发生了什么!

#include <iostream>
using namespace std;

int getUserInput() {                                        // Get user numbers
    cout << "Enter a number: " << endl;
    int userInputNumber;
    cin >> userInputNumber;
    return userInputNumber;
}

char getUserOper() {                                        // Get user math operator
    cout << "Enter a math operator: " << endl;
    int userInputOper;
    cin >> userInputOper;
    return userInputOper;
}

int doMath(int x, char oper, int y) {                       // Does math based on provided operator
    if(oper=='+') {
        return x + y;
    }
    if(oper=='-') {
        return x - y;
    }
    if(oper=='*') {
        return x * y;
    }
    if(oper=='/') {
        return x / y;
    }
    else {
        return 0;
    }
}

void printResult(int endResult) {                           // Prints end result
    cout << endResult;
}

int main() {
    int userInputOne = getUserInput();
    char userOper = getUserOper();
    int userInputTwo = getUserInput();
    printResult(doMath(userInputOne, userOper, userInputTwo) );
}

4 个答案:

答案 0 :(得分:3)

当你在getUserOper中使用char时使用int

char getUserOper() {                                        // Get user math operator
    cout << "Enter a math operator: " << endl;
    char userInputOper;
    cin >> userInputOper;
    return userInputOper;
}

答案 1 :(得分:1)

在getUserOper中使用char

char getUserOper() {                                        // Get user math operator
        cout << "Enter a math operator: " << endl;
        char userInputOper;
        cin >> userInputOper;
        return userInputOper;
    }

答案 2 :(得分:1)

当你做cin&gt;&gt; userInputOper \ n仍在缓冲区中,然后第二次使用。导致无效输入存在和未定义的行为。

cin >> userInputOper; 
//cin.ignore(); // removes one char from the buffer in this case the '\n' from when you hit the enter key, however " " is a delimiter so if the user enters 23 54 only 23 gets entered and 54 remains in the buffer as well as the '\n' which will get used on the next call
cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n'); // clears everything in the buffer
return userInputOper;

此外,您应该检查输入错误

int myInt;
while ( !(cin >> myInt) )
{
cout << "Bad input try again\n";
cin.clear();  // this only clears the fail state of the stream, doesn't remove any characters
cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n'); // removes all chars from the buffer up to the '\n'
}
cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');

你应该为操作员收取一个字符,虽然不是完全必要的。当用户输入大于char 255的数字时,您将遇到问题。

答案 3 :(得分:1)

char getUserOper() {                                        // Get user math operator
        cout << "Enter a math operator: " << endl;
        char userInputOper;
        cin >> userInputOper;
        return userInputOper;
    }

您需要使用 char 而不是 int