为什么不在 switch 语句中处理字符?C++

Tah*_*hir 2 c++

我试图通过使用 char +、-、/、* 来获取和处理用户决定,为什么 switch 语句忽略它们,因此我在我的代码中看不到任何错误。

#include <iostream>
using namespace std;

void optionMenu();
double UserOutput(int);

int main ()
{
    int UserChoice;

    optionMenu();
    cout << " Choice: ";
    cin >> UserChoice;
    UserOutput(UserChoice);


    return 0;
}
void optionMenu()
{
    cout << " Select your choice" << '\n';
    cout << " + for Addition" << '\n';
    cout << " - for Subtraction" << '\n';
    cout << " / for Division" << '\n';
    cout << " * for Multiplication" << '\n';
}
double UserOutput (int UserChoice)
{
    int value1, value2;
    switch (UserChoice)
    {
        case '+':
        cout << " Enter First Number: "; cin >> value1;
        cout << " Enter Second Number: "; cin >> value2;
        cout << " The result for the Entered numbers is equal to: [" << (value1 + value2) << "]" << '\n';
        break;
        case '-':
        cout << " Enter First Number: "; cin >> value1;
        cout << " Enter Second Number: "; cin >> value2;
        cout << " The result for the Entered numbers is equal to: [" << value1 - value2 << "]" << '\n';
        break;
        case '/':
        cout << " Enter First Number: "; cin >> value1;
        cout << " Enter Second Number: "; cin >> value2;
        if(value2)
        cout << " The result for the Entered numbers is equal to: [" << value1 / value2 << "]" << '\n';
        else
            cout << " Not Allowed or Infinity, Try again!" << '\n';
        break;
        case '*':
        cout << " Enter First Number: "; cin >> value1;
        cout << " Enter Second Number: "; cin >> value2;
        cout << " The result for the Entered numbers is equal to: [" << value1 * value2 << "]" << '\n';
        break;
        default:
            cout << " Invalid Input Try again" << '\n';
            break;

    }
}
Run Code Online (Sandbox Code Playgroud)

sco*_*001 8

您的问题就在这里:

int UserChoice;

optionMenu();
cout << " Choice: ";
cin >> UserChoice;
Run Code Online (Sandbox Code Playgroud)

您要求用户输入 +、-、/、* 字符,但您正在将其读入int变量。这将导致std::cin失败并被0写入UserChoice(见这里更多信息)。

相反,将该选项读作char

char UserChoice;
//^^

optionMenu();
cout << " Choice: ";
cin >> UserChoice;
Run Code Online (Sandbox Code Playgroud)

请注意,您还有以下警告:

main.cpp:60:1: warning: no return statement in function returning non-void [-Wreturn-type]
Run Code Online (Sandbox Code Playgroud)

这是因为您已指定UserOutput为返回 a 的函数double,但您从未返回任何内容。您可能希望将其更改为void函数以避免将来出现错误/错误。