c++ - Switch Case 总是默认

标签 c++ switch-statement case

我正在尝试制作一个小型操作系统,它从一个开关...盒中获取响应以转到一个微型游戏或一个简单的计算器。但是,无论我提供什么输入(即使是正确的输入),输出始终是默认值。 我正在使用的编译器(Microsoft Visual Studio;可能是问题所在)没有给我任何错误,而且我找不到或想不到任何错误。你们中的一些真正擅长这方面的人对我的问题有任何答案吗?

#include "stdafx.h"
#include <iostream>
#include <limits>

using namespace std;

int calc() {

char op;
float num1, num2;

cout << "Enter operation:";
cin >> op;

cout << "Enter two numbers:";
cin >> num1 >> num2;

switch (op)
{
case '+':
    cout << num1 + num2;
    break;

case '-':
    cout << num1 - num2;
    break;

case '*':
    cout << num1 * num2;
    break;

case '/':
    cout << num1 / num2;
    break;

default:
    cout << "That is not an operation";
    break;
}

return 0;
};

int main()
{
char answer;

cout << "Welcome to the FR Operating System. \n";
cout << "If you want to go to the calculator, type in 'Calc'. \n";
cout << "If you want to go to the game, type in 'Game'. \n";

cin >> answer;

switch (answer) {
case 'Calc' || 'calc':
    cout << "Welcome to the calculator. \n";
    break;

case 'Game':
    cout << "Welcome to our game, 'A Day in the Life'. \n";
    break;

default:
    cout << "That is an invalid answer. This has caused the system to crash. \n";
    break;
}

atexit([] { system("PAUSE"); });

return 0;

}

最佳答案

  1. 'Game' 不是有效字符串
  2. 即使您将其替换为有效字符串 "Game"switch 也不适用于字符串。

因此,要么在你的开关中使用单个字符,要么使用 if-else block ,你通过 比较 std::string ==

std::string answer;
cin >> answer;
if (answer == "Calc" || answer == "calc")
    //...
else if (answer == "Game")
    //...
else
    // invalid 

关于c++ - Switch Case 总是默认,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50730767/

相关文章:

Powershell 控制台菜单选项 - 需要添加换行符吗?

c++ - 如何显示类中某些内容的枚举值?

c++ - 是否可以从 stdin 输入指向指针的地址?

c++ - 字符串指针的排序 vector

sql - SQL SERVER 中的排序依据和大小写

sql - 在 PostgreSQL 中添加负间隔

MySQL SUM 和 CASE 可以在 DISTINCTROW 上使用吗?

c++ - 区分类型

JavaScript switch 语句 1-100

java - java中使用数组实现堆栈的切换情况