Added some input validation examples

This commit is contained in:
left_adjoint 2024-01-16 11:30:11 -08:00
parent 8b437a152b
commit d2366ac685
2 changed files with 52 additions and 0 deletions

21
input1.cpp Normal file
View File

@ -0,0 +1,21 @@
#include <iostream>
using namespace std;
/*
what happens if you enter a character? what happens if I enter 12.2?
how do I abstract this?
*/
int main() {
int ourInput;
cout << "Enter a whole number, only." << endl;
cin >> ourInput;
while(cin.fail()){
cout << "Nope, enter a number" << endl;
cin.clear();
cin.ignore(256,'\n');
cin >> ourInput;
}
return 0;
}

31
input2.cpp Normal file
View File

@ -0,0 +1,31 @@
/*
Now we're going to abstract the idea of checking whether a number is correct into its own function
Otherwise this is going to be just like input1.cpp
*/
#include <iostream>
using namespace std;
int readInt(){
int ourInput;
cout << "Enter a whole number, only." << endl;
cin >> ourInput;
while(cin.fail()){
cout << "Nope, enter a number" << endl;
cin.clear();
cin.ignore(256,'\n');
cin >> ourInput;
}
cin.ignore(256,'\n'); // check what happens if you comment this line out and enter something like 10.3 as your first number, does it make sense why we need it?
return ourInput;
}
int main() {
int myInt = readInt();
int anotherInt = readInt();
cout << "Let's add our numbers together: " << myInt + anotherInt << endl;
return 0;
}