so I was told to do the following:
Reproduce the function isValidInt to validate the format for
an integer which has been entered using the keyboard.
Test your function using the following test cases:
-1234
5674.25
$1700
Reproduce the function readInt that uses isValidInt.
Demonstrate your function.
Write a function isValidDouble to validate the format for
a real number which has been entered using the keyboard.
Test your function using the following test cases:
-23486.33
.67425
$24576.79
54,765.98
76.543.20
Write a function readDouble that uses isValidDouble.
Demonstrate your function.
But as you will see from my code I can not figure out how to tie it all to gather to use these functions I have made. If some one could show me how I would greatly appreciate it!
Note: it keeps telling me "invalid selection please try again" even when I put type the right letters in....
also how do I keep it from going into an infinite loop?
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 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
|
// main.cpp
// Program 11
// Created by William Blake Harp on 8/6/14.
#include <iostream>
using namespace std;
bool isvalidInt(string);
int readInt(string prompt);
double readDouble(string prompt);
int main()
{
int number;
char selection;
do
{
cout << "Enter 'I' for integer or 'D' for double: " << endl;
cin >> selection;
if (selection == 'i' || selection == 'I')
{
number = readInt("Enter an int: ");
}
else if(selection == 'd' || selection == 'D')
{
number = readDouble("Enter a double int: ");
}
else
{
cout << "invalid selection please try again\n\n";
}
}while (selection != 'i' || selection != 'I' || selection != 'd' || selection != 'D');
return 0;
}// End Main.
bool isvalidInt(string str)
{
int start = 0; //start position in the string
int i; //position in the string
bool valid = true; //assume a valid integer
bool sign = false; //assume no sign
//check for an empty string
if (str.length() == 0) valid = false;
if (valid)
if (str.at(0) == '-' || str.at(0) == '+')
{
sign = true;
start = 1;
if (sign && str.length() == 1)
valid = false;
}
else if(! isdigit(str.at(0)))
{
valid = false;
}
return 0;
}// End is valid int.
int readInt(string prompt)
{
string strVal("");
do
{
cout << prompt;
getline(cin, strVal);
} while (! isvalidInt(strVal));
while (! isvalidInt(strVal))
{
return atoi(strVal.c_str());
}
return 0;
}// End readInt.
double readDouble(string prompt)
{
string strVal("");
do
{
cout << prompt;
getline(cin, strVal);
} while (! isvalidInt(strVal));
while (! isvalidInt(strVal))
{
return atoi(strVal.c_str());
}
return 0;
}// End read double.
|