I'm trying to make a function work without the possibility of an infinite loop. The function has two inputs: an operator and one operand and returns a sum. The inputs would look like -8 or *7 for example. The problem I have is if I enter in a "--" instead of -8, it will go to an infinite loop.
Code:
#include <iostream>
#include <cmath>
using namespace std;
void repeat(char, float, float&);
float operand1, sum ;
int SENTINEL;
char operator1;
int main()
{
sum = 0;
do
{
cout << "enter asterisk or minus sign and a number" << endl;
cin >> operator1 >> operand1;
if ((operator1 == '-')||(operator1 == '*')) //if-statement #1
repeat(operator1, operand1, sum);
if ((operator1 == '='))
SENTINEL = 1;
cout << "Total = " << sum << endl;
} while (SENTINEL != 1);
return 0;
}
void repeat(char choice, float z, float& total)
{
switch (choice)
{
case '-':
total -= z;
break;
case '*':
total *= z;
break;
case '+': //shouldn't be able to add if... if-statement #1 is working correctly
total += z;
break;
}
}
In the version below, I added another do-while statement to repeat the inputs if a positive number wasn't entered in for the operand. The outcome of this is it doesn't do the infinite loop, but just stops letting you enter in the operator and operand.
Code:
#include <iostream>
#include <cmath>
using namespace std;
void repeat(char, float, float&);
float operand1, sum ;
int SENTINEL;
char operator1;
int main()
{
sum = 0;
do
{
cout << "enter asterisk or minus sign and a number" << endl;
do{
cin >> operator1 >> operand1;
}while (!(operand1 > 0));
if ((operator1 == '-')||(operator1 == '*')) //if-statement #1
repeat(operator1, operand1, sum);
if ((operator1 == '='))
SENTINEL = 1;
cout << "Total = " << sum << endl;
} while (SENTINEL != 1);
return 0;
}
void repeat(char choice, float z, float& total)
{
switch (choice)
{
case '-':
total -= z;
break;
case '*':
total *= z;
break;
case '+': //shouldn't be able to add if... if-statement #1 is working correctly
total += z;
break;
}
}
With either of these versions it lets me enter in random numbers like 74 or 12 (and no operators) and the loop repeats once. What I would like to be able to do is enter in two random characters like -- or %@ and have the loop repeat just once as well to re-enter the inputs. Any ideas?