im working on a calculator and im having difficulty working
out how to test the user entered number ive done it before but
ive forgot how to do it the easy way, ive tried loads of
difficult ways and none work on my compiler or when integrated
into my program any help would be gratefully recieved. i need to loop until the correct input has been entered by the user
// scientific calculator
#include <iostream.h> // inut and output
#include <ctype.h> // the header file allows the toupper function
#include <windows.h> // allows windows system functions system("CLS")
#include <math.h> // allows the sqrt sin, cos, log, tan, alog, and acos math functions
// slimmed down version of the code im working on
double getNumber() // cant sus out how to validate user input
// within this function tried the cin.good method and failed
// to get it working within my code
{
double b;
cout <<"Please enter a number : ";
cin >>b;
return b;
}
double multiply(double* x, double* y)
{
return *x * *y;
}
int main()
{
double* x;
double* y;
double z;
char s;
double num1, num2;
cout <<" Enter * to multiply "<<"\n";
cout <<"Please enter your option : ";
cin >> s;
system("CLS");
s = toupper(s);
switch (s)
{
case '*' :
cout <<"********************************"<<"\n";
cout <<"* You opted to multiply *" <<"\n";
cout <<"********************************" <<"\n";
x = &num1;
y = &num2;
*x = getNumber();
*y = getNumber();
z = multiply(x, y);
cout <<*x << " * " <<*y << " = " << z << "\n";
cout <<"The pointer are : " << &num1 <<" and " << &num2 <<"\n";
break;
default:
cout <<"***** Do you wish to perform a calculation ***** " <<"\n";
}
return 0;
}
// i tried the following method but it wont work on my compiler
// it should work
#include <iostream>
#include <cstdlib> // system call
#include <ctype> // isdigit()
#include <cmath> // atof (ASCII to float (double) )
#include <iomanip> // setprecision()
inline void pause() { system("PAUSE"); }
int main(void)
{
char* input = " ";
double numVal;
bool valid = true;
std::cout << "Enter a numeric value: -> ";
std::cin >> input;
for ( unsigned int i = 0; i < strlen(input); i++ ){
if ( !isdigit(input[i]) && input[i] != '.'){
std::cerr << "\nError! " << "'" << input[i] << "'"
<< " is an invalid character.\n\n";
valid = false;
}
}
if ( valid ){
numVal = atof(input);
std::cout << setiosflags(std::ios::fixed)<< std::setprecision(2)
<< "\nnumVal = " << numVal << "\n\n";
}
pause();
return 0;
}