0

I am trying to get user input and then check if the input is an integer and then return it. If I enter an integer then it will return the value but if the input is a string then it will endlessly output >>>Failed

I was using SO Answer as the base.

#include "stdafx.h"
#include <iostream>


int getRandomNumber(int maxNum) {
    return rand() % maxNum + 1;
}

int getIntInput() {
    int input;

    while (true) {
        std::cout << ">>> ";
        std::cin >> input;
        std::cin.clear();
        std::cout << std::flush;

        if (std::cin.fail() || input < 0) {
            std::cout << "Failed";
            continue;
        }

        break;
    }

    return input;
}


int main() {
    int numGuessed;
    int randomNum = getRandomNumber(100);

    numGuessed = getIntInput();
}
Joshua Nixon
  • 1,379
  • 2
  • 12
  • 25

1 Answers1

1

Your main problem is that you only clear the error condition but never flush the offending input, so the input stream stays at the erroneous characters. The common way is to read (and discard) a full line for a failed conversion:

while (true) {
    std::cout << ">>> ";
    std::cin >> input;
    std::cout << std::flush;

    if (std::cin.eof()) {    // do not try to read past an eof!
        input = 0;
        break;
    }
    if (std::cin.fail() || input < 0) {
        std::string line;
        std::cin.clear();              // reset the fail flag
        std::getline(std::cin, line);  // read until end of line
        std::cout << "Failed";
        continue;
    }

    break;
}
Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252