cin >> int given a string assigns int to 0

Viewed 110

The issue that I'm having is that if you input any string the cin will assign the int to 0. An interesting finding is that if you later take cin to a string you get the entire string you put in for the int. cin.fail() always returns true for some reason, even with cin.ignore(), etc and if( cin >> startingPosition ) also always returns true. So, how do I get it to catch an even recognize that it's a string and not an int? As in, how do I have it loop again if it is a string?

int getUserPosition(bool volatileCall = false) {
    cout << "Which slot do you want to drop the chip in (0-8)? " << endl;
    int startingPosition;
    cin >> startingPosition;
    while (startingPosition >= WIDTH || startingPosition < 0) {
    cout << "Invalid slot." << endl << endl;

        if (volatileCall) {
            return -1;
        }
        cout << "Which slot do you want to drop the chip in (0-8)? " << endl;
        cin >> startingPosition;
        cout << startingPosition << endl;

    }
    return startingPosition;
}
1 Answers

you must save result from cin

isNumber = (cin >> startPosition);

the whole code will look like

int getUserPosition(bool volatileCall = false) {
    cout << "Which slot do you want to drop the chip in (0-8)? " << endl;
    int startingPosition;
    bool isNumber = (cin >> startingPosition);
    while(isNumber && (startingPosition >= WIDTH || startingPosition < 0)) {
        cout << "Invalid slot." << endl << endl;
        if (volatileCall) {
            return -1;
        }
        cout << "Which slot do you want to drop the chip in (0-8)? " << endl;
        isNumber = (cin >> startingPosition);
        cout << startingPosition << endl;
    }
    return startingPosition;
}
Related