For this problem I know I need some kind of flush function to fix it, I have a program that runs as a calculator and everything works fine accept if I input a character the program does an infinite loop because its expecting a float, how do I get it to where the program continues on without the infinite loop, here is my code.
Code:
// Program 3
// 10/17/2006
// This program is a calculator
#include <iostream>
#include <cmath>
#include <string>
#include <stdio.h>
using namespace std;
void instructions ()
// Repeated instructions for the user
{
cout << "Type your operation then the number;" << endl;
}
void main ()
{
float accum, num;
char op;
op = 0;
accum = 0.0;
// Beggining instructions for the user
cout << "type * for multiplication;" << endl;
cout << "type / for division;" << endl;
cout << "type - for subtraction;" << endl;
cout << "type + for addition;" << endl;
cout << "type q, Q, or = to quit;" << endl;
// Calculator process
while ((op!='q')&& (op!='Q') && (op!='='))
{
instructions ();
cin >> op;
if (op!='q'&& op!='Q' && op!='=')
{ switch (op)
// The operations for the calculator
{
case '+':
cin >> num;
accum = accum + num;
cout << accum << " " << endl;
break;
case '-':\
cin >> num;
accum = accum - num;
cout << accum << " " << endl;
break;
case '*':
cin >> num;
accum *= num;
cout << accum << " " << endl;
break;
case '^':
cin >> num;
accum = pow(accum, num);
cout << accum << " " << endl;
break;
case '/':
cin >> num;
if (num == 0)
{
// If the user inputs zero it won't crash
cout << "Error: You Can't divide by a '0'.";
cout << endl << endl; accum;
} if (num != 0)
{
accum = (accum / num);
cout << accum << " " << endl;
}
break;
default:
cout << "invalid operation" << endl;
} }
if (num == '\n' && op != 'q' && op != 'Q' && op != '=')
{cout << "Invalid input" << endl; }
num = '\n';
if (op =='q'|| op == 'Q' || op == '=')
{cout << "Thanks for using my program " << endl;}
}
system("pause");
}
Comment