带有字符值的 if 语句

if statements with char values

本文关键字:if 语句 字符      更新时间:2023-10-16

所以我正在尝试在这里编写一个简单的基本游戏,其中包含基本C++,当我尝试执行此游戏时

// global variabless
const char UP = 'w', LEFT = 'a', DOWN = 's', RIGHT = 'd'; // player movement choices
char playerMove; // goes with askPlayer
void askPlayer()
{
    char choice;
    cout << "Use the WASD keys to move: ";
    cin >> choice;
    int worked;
    do{
        if (choice == 'w' || choice == 'W')
        {
            playerMove = UP;
            worked = 1;
        }
        else if (choice == 'a' || choice == 'A')
        {
            playerMove = LEFT;
            worked = 1;
        }
        else if (playerMove == 's' || playerMove == 'S')
        {
            playerMove = DOWN;
            worked = 1;
        }
        else if (playerMove == 'd' || playerMove == 'D')
        {
            playerMove = RIGHT;
            worked = 1;
        }
        else
        {
            cout << "Invalid entry." << endl;
            worked = 0;
        }
    } while (worked != 1);
    return;
}

它适用于用户输入字母。Xcode 说 (lldb),然后页面填满数字,停止运行后,它说"程序以退出代码结束:9"。即使您输入有效值之一,它也会这样做

用户输入第一个值后,您永远不会提示输入另一个值:

cin >> choice; // <==
int worked;
do {
    // ..
} while (worked != 1);

只需将输入移动到循环中:

int worked;
do {
    cin >> choice; // possibly with cout prompt too
    // rest as before
} while (worked != 1);

你的输入在循环之外,你的变量worked是未初始化的(虽然它不是代码中的错误,但初始化变量更干净),它应该bool类型。 整个代码可以通过 switch 语句来简化:

void askPlayer()
{
    do {
        char choice;
        cout << "Use the WASD keys to move: ";
        cin >> choice;
        switch( choice ) {
            case 'w' : case 'W' :
                playerMove = UP;
                break;
            case 'a' : case 'A' :
                playerMove = LEFT;
                break;
            case 's' : case 'S' :
                playerMove = DOWN;
                break;
            case 'd' : case 'D' :
                playerMove = RIGHT;
                break;
            default:
                cout << "Invalid entry." << endl;
                continue;
        }
    } while( false );
    return;
}