It's a bit lengthy... but here it goes.
Here is the problem:
Using the getDouble function as an example write your own function readMoney, which reads amount of dollars and cents from the user. The user input should be in the form:
$123.34
That is, it should start with the dollar sign, and then it should have the amount of dollars, then the decimal point, and then 2-digit amount of cents. It should end with any space symbol or a dot. Your function should return 2 integer values (one for dollars and another for cents).
Here is getDouble:
#include <iostream.h>
#include <ctype.h>
#include <stdlib.h>
// function: getDouble
// goal: The function reads character by character from the
// standard input (cin) and converts them into a floating
// point number. It stops when it reads any character
// but +, -, decimal point or a digit.
// As the result it returns the number read.
double getDouble(void)
{
char ch;
int sign = 1;
double res = 0;
double factor = 10;
cin.get(ch); // read the very first symbol from the user
// check if the first symbol is a sign
if( ch=='-' || ch=='+' ){
if( ch == '-' ) sign = -1;
cin.get(ch); // read the next symbol
}
// repeat the loop while it's a correct symbol
while( isdigit(ch) || (ch=='.' && factor>0.1) ){
if( isdigit(ch) ){
if( factor > 0.1 ){
// we haven't read the decimal point yet
res = factor * res + (ch - '0');
}
else{
// we have read the decimal point by this time
res += (ch - '0') * factor;
factor /= 10;
}
}
else{ // we just read the decimal point
factor = 0.1;
}
cin.get(ch); // read the next symbol
}
return res*sign;
}
int main(void)
{
double num;
cout<<"Enter a floating point number ";
num = getDouble(); // using the new function to read the user's input
cout<<"You entered: "<<num<<endl;
return 0;
}
My question is how do I output dollars and cents from the function as separate variables.