dimanche 3 mars 2019

Detect blank input on integer type variable?

I am currently working on a text based adventure game as a project for class. I have mostly everything started and working fine. The only problem is when I ask the user which room they want to change to, if they enter a blank input, then a message should output saying "You must choose a room." For the life of me I cannot figure it out. Any help is much appreciated.

Code:

#include <iostream>
#include <cstdlib>
#include <ctime>

using namespace std;

int main() {

bool game_play = true;
bool game_start = true;
int room_change;
int room_current = 0;

while (game_play == true) {
    if (game_start == true) {
        srand((unsigned int)time(NULL));
        room_change = rand() % 2 + 1;
        game_start = false;
    }
    else {
        for (bool check = false; check == false;) { // Check if input is invalid
            cin >> room_change;
            if (cin.fail()) {
                cout << "Choose an existing room.";
                cin.clear();
                cin.ignore();
            }
            else if (room_change == room_current) {
                cout << "You're already in that room.";
            }
            else {
                check = true;
            }
        }
    }
    switch (room_change) {
    case 1:
        cout << "You are in room 1.";
        room_current = 1;
        break;
    case 2:
        cout << "You are in room 2.";
        room_current = 2;
        break;
    case 3:
        game_play = false;
        break;
    default:
        cout << "That room doesn't exist.";
    }
}
return 0;
}

Aucun commentaire:

Enregistrer un commentaire