我目前正在学习和使用 C++,我想知道为什么我的 switch 语句只响应一半的情况?它仅在从整数中减去时响应。请注意,我尽可能成为初学者,所以任何建议都会非常有帮助。
#include <fstream>
#include <iostream>
#include <windows.h>
#include <conio.h>
using namespace std;
#define KEY_UP 72
#define KEY_DOWN 80
#define KEY_LEFT 75
#define KEY_RIGHT 77
#define SPACE_BAR 32
void startingCoord (int & x, int & y)
{
cout << "Starting coord" <<endl;
cin >> x >> y;
}
void printGrid(int x, int y)
{
for (int a = 0; a < 10; a++)
{
for (int b = 0; b < 10; b++)
{
if (a + 1 == x && b + 1 == y)
{
cout<<" 0 ";
}
else
{
cout<<" - ";
}
}
cout<<endl;
}
}
int main ()
{
int c = 0, x = 0, y = 0;
startingCoord(x, y);
while (true)
{
printGrid(x, y);
switch (c = getch()){
case SPACE_BAR:
return 0;
case KEY_DOWN:
x++;
case KEY_RIGHT:
y++;
case KEY_UP:
x--;
case KEY_LEFT:
y--;
default:
return 0;
}
cout<<x<<" "<<y;
}
}
最佳答案
改变这个:
case KEY_DOWN:
x++;
为此:
case KEY_DOWN:
x++;
break;
并且对每个没有return
语句的情况都做同样的事情。
如果没有 break
语句,控制流将继续到条件刚好满足的 case 之后的 case。
关于c++ - 为什么我的 switch 语句没有响应一半的情况?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50077863/