2

我正在尝试学习一些 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

4 回答 4

3

您应该在 getUserOper 中使用 char 时使用 int

char getUserOper() {                                        // Get user math operator
    cout << "Enter a math operator: " << endl;
    char userInputOper;
    cin >> userInputOper;
    return userInputOper;
}
于 2012-08-17T16:29:34.290 回答
1

char在 getUserOper 中使用

char getUserOper() {                                        // Get user math operator
        cout << "Enter a math operator: " << endl;
        char userInputOper;
        cin >> userInputOper;
        return userInputOper;
    }
于 2012-08-17T16:28:42.277 回答
1

当您执行 cin >> 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 的数字时,您会遇到问题。

于 2012-08-17T16:31:11.723 回答
1
char getUserOper() {                                        // Get user math operator
        cout << "Enter a math operator: " << endl;
        char userInputOper;
        cin >> userInputOper;
        return userInputOper;
    }

您需要使用char而不是int

于 2012-08-17T16:33:06.283 回答