我正在尝试制作一个小型操作系统,它从一个开关...盒中获取响应以转到一个微型游戏或一个简单的计算器。但是,无论我提供什么输入(即使是正确的输入),输出始终是默认值。 我正在使用的编译器(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;
}
最佳答案
'Game'
不是有效字符串- 即使您将其替换为有效字符串
"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/