Simple Calculator program

Aug 11, 2014 at 1:36am
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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>

using namespace 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.
Last edited on Aug 11, 2014 at 1:37am
Aug 11, 2014 at 4:16am
Try to avoid using global variables. It can get you into trouble later on with scopes. So initialize repeat and response inside the main.

Also, when ignoring something, in order to discard any unprocessed characters, use

1
2
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

Be sure to use #include <limits> when using this.

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"
Last edited on Aug 11, 2014 at 4:25am
Aug 11, 2014 at 8:07pm
Hmmm, maybe I'm not converting num1 and num2 into a char correctly but I'm still having the same issue.
Aug 11, 2014 at 10:35pm
You're calling cin >>num1 twice. Remove it from line 21.
Aug 12, 2014 at 5:28pm
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.
Topic archived. No new replies allowed.