republikunt
republikunt

Reputation: 41

if statements with char values

So I'm trying to write an easy basic game here with basic C++, and when I try to execute this

// 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;
}

It works up to the user entering a letter. Xcode says (lldb) then the page fills up with numbers, and after you stop the run, it says "Program ended with exit code: 9". It does this even if you enter one of the valid values

Upvotes: 0

Views: 1387

Answers (2)

Slava
Slava

Reputation: 44278

Your input is outside the loop, your variable worked is uninitialized ( though it is not a error in your code but is cleaner to initialize your variables) and it should have bool type. Whole code can be simplified by the switch statement:

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;
}

Upvotes: 1

Barry
Barry

Reputation: 303880

You never prompt for another value after the user enters the first one:

cin >> choice; // <==
int worked;

do {
    // ..
} while (worked != 1);

Just move the input into the loop:

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

Upvotes: 3

Related Questions