I am trying to allow only integrers to be inputted
Should Reject:
- 5h
- 3.4
- 3.gh
- 3.0
- htr
Should Accept:
- -5
- 0
- 78
Current Code
int getIntInput() {
int userInput;
while (true) {
std::cout << "> ";
std::cin >> userInput;
std::cout << std::flush;
if (std::cin.fail()) {
std::string cinBuffer;
std::cin.clear();
std::getline(std::cin, cinBuffer);
continue;
}
break;
}
return userInput;
}
Updated Code
Issues:
Accepts all rejections excluding "htr" (No numerals)
int getIntInput() { std::string rawInput; int parsedinput; while (true) { std::cout << "> "; std::getline(std::cin, rawInput); std::cout << std::flush; try { parsedinput = std::stoi(rawInput); } catch (std::invalid_argument & e) { continue; } catch (std::out_of_range & e) { continue; } break; } return parsedinput; }
Finished Code
Accepts only integers with an optional parameter which will allow negative numbers to be accepted or rejected.
int getIntInput(bool allowNegatives = true) { bool validIntInput; std::string rawInput; int parsedinput; while (true) { validIntInput = true; // Grabs the entire input line std::cout << "> "; std::getline(std::cin, rawInput); std::cout << std::flush; for (int i = 0; i < rawInput.length(); i++) { // Checks to see if all digits are a number as well as to see if the number is a negative number if (!isdigit(rawInput[i]) && !(allowNegatives && i == 0 && rawInput[i] == '-')) { validIntInput = false; break; } } if (!validIntInput) { continue; } else { try { // Try parse the string to an int parsedinput = std::stoi(rawInput); // Catch all possible exceptions, another input will be required } catch (...) { continue; } // If the code reaches here then the string has been parsed to an int break; } } return parsedinput;}