Hi. I just completed a summer school course on C++ with no prior programming knowledge, so I haven't been doing this for long. For fun, I knew I missed some concepts and decided to improve some of the programs I have done. One of these was to create a simple calculator. I've been adding while loops to account for incorrect input, and it sorta/kinda works. Here's a snippet:
#include <iostream>
usingnamespace std;
bool repeat;
char response;
int main()
{
char operation;
double num1, num2;
repeat = true;
while (repeat)
{
cout << "Enter an operand, i.e. (+, -, *, /) : ";
cin >> operation;
cout << endl;
cout << "You will enter two numbers.";
cout << endl << "1st number: ";
cin >> num1;
while (!(cin >> num1))
{
cin.clear();
cin.ignore(100, '\n'); // i feel like this is the culprit?
cout << "Invalid input. Enter a digit. ";
}
cout << endl;
If I enter something that is not a digit, then the 'Invalid input' message will come up and allow me to try again until I get it right. But if I do put in a number and hit Enter, then nothing will happen. If I enter the number again despite no prompt and hit enter again, then it will read into num1 and run the rest of the program correctly with similar circumstances for num2.
So, is my ignore statement no good? I'm trying to get rid of having to put in the number twice if I was correctly entering a number the first time.
As for the error checking for int values, I like to convert all input into a char value and then find the ASCII value. If the ASCII value is not within (or equal to) a certain range for the int's, then go into the "Invalid input"
You got it. Thanks, Lowest0ne. I guess I thought I had to do the cin function beforehand if I was doing a while !(cin >> num1) or it'd just toss in an arbitrary value as if I'd left it blank.