c++ - 为什么我的 switch 语句没有响应一半的情况?

标签 c++

我目前正在学习和使用 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/

相关文章:

c++ - 如何在VS项目中静态链接没有dll文件的cpprest?

C++ 和成员函数指针

c++ - 管理共享指针 C++

c++ - 如何在函数内部创建一个数组,然后使用该数组创建另一个数组?

python - 在 python 中的 byref vector 参数上使用 ctypes 进行 DLL 转换

c++ - 使用范围初始化 vector 与 lambda 内联初始化

c++ - 在 Qt C++ 中使用 OpenSSL

c++ - 在 Qt 项目、Visual Studio 中添加按钮单击处理程序

c++ - 在 3D 中查找 X、Y 和 Z 轴的角度 - OpenGL/C++

shm_open : DSO Missing From Command Line 上的 C++ Boost 库 undefined reference