[In C++] How do you handle wrong input datatypes? My input was \"w\" or \"w w w
ID: 3853229 • Letter: #
Question
[In C++] How do you handle wrong input datatypes?
My input was "w" or "w w w w" when it's supposed to be a "single digit" integer input.
I want it to be able to do error checking if a string or char is typed and ask again to type integers but instead I get an infinite loop.
Here is my code:
main(){
int a, b, c, d, sum = 0;
cout << "Type your four digits in the format (1 2 3 4) " << endl;
cin >> a >> b >> c >> d;
//Checking for single digits
while((a > 10 || a < 0) || (b > 10 || b < 0) || (c > 10 || c < 0) || (d > 10 || d < 0)){
cout << "Incorrect input, use single digits only (0-9)" << endl;
cin >> a >> b >> c >> d;
}
}
Explanation / Answer
Hi,
I have fixed the issue and highlighted the code changes below.
#include <iostream>
using namespace std;
int main(){
int a, b, c, d, sum = 0;
cout << "Type your four digits in the format (1 2 3 4) " << endl;
cin >> a >> b >> c >> d;
//Checking for characters
while(cin.fail()){
cout << "Incorrect input, use single digits only (0-9)" << endl;
cin.clear();
cin.ignore(256,' ');
cin >> a >> b >> c >> d;
}
//Checking for single digits
while((a > 10 || a < 0) || (b > 10 || b < 0) || (c > 10 || c < 0) || (d > 10 || d < 0)){
cout << "Incorrect input, use single digits only (0-9)" << endl;
cin >> a >> b >> c >> d;
}
}
Output:
sh-4.2$ g++ -o main *.cpp
sh-4.2$ main
Type your four digits in the format (1 2 3 4)
s 3 4 5
Incorrect input, use single digits only (0-9)
1 2 3 14
Incorrect input, use single digits only (0-9)
1 2 3 4
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.