This is my first post on here, and I am very new to programming/C++ (literally just a couple of weeks into this rabbit hole). I have this test project up in Microsoft Visual Studio 2017, and I am trying to figure out how to completely foolproof user input while using cin. If I am asking for an int, and I only want a 1 or a 0, I want there to be absolutely no way for someone to place in something like a 2, or an n, or a space between an incorrect and correct response like "n 1". Currently, I have gotten to the point in which the only way I can seem to create an undesired result is if I enter a correct integer first (0 or 1) and then follow it up with a space and any other character, and this pattern can be followed with an indefinite number of spaces and characters after the initial correct one (0 a 42 f 9130) etc. Besides just getting the desired result with even more messy code, I'm wondering if I'm just missing some in-built functions that I have not heard of yet in which can make this process much more efficient. Here is what I wrote to get to this point:
#include <iostream>
#include <string>
#include <climits>
using namespace std;
int trap;
int wrongNumber();
int numOnly() {
while (cin.fail())
{
// Using someone else's code for this while statement to figure out how to not take a char input when using an int
// Update: Turned this into a function to be called on whenever cin has a chance to fail because users don't listen.
cin.clear(); // clear input buffer to restore cin to a usable state
cin.ignore(INT_MAX, '\n'); // ignore last input
system("CLS");
cout << "----------------------------------" << endl;
cout << "| You can only enter a number. |" << endl;
cout << "| Would you like to pick a card? |" << endl;
cout << "| Type 1 for yes or 0 for no! |" << endl;
cout << "----------------------------------" << endl;
cin >> trap;
}
if (trap != 1 && trap != 0) {
system("CLS");
wrongNumber();
}
return trap;
}
int wrongNumber() {
// At least I made this fail-safe on my own!
while (trap != 1 && trap != 0) {
system("CLS");
cout << "----------------------------------" << endl;
cout << "| That is not a 1 or a 0! |" << endl;
cout << "| Would you like to pick a card? |" << endl;
cout << "| Type 1 for yes or 0 for no! |" << endl;
cout << "----------------------------------" << endl;
cin >> trap;
}
if (cin.fail()) {
system("CLS");
numOnly();
}
return trap;
}
int main() {
cout << "----------------------------------" << endl;
cout << "| Would you like to pick a card? |" << endl;
cout << "| Type 1 for yes or 0 for no! |" << endl;
cout << "----------------------------------" << endl;
cin >> trap;
while (cin.fail())
{
numOnly();
}
if (trap != 1 && trap != 0) {
wrongNumber();
}