Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Christian Ballard
- // COSC 1336 - 001
- // This program should validate user input for doubles.
- // Febuary 9, 2015
- #include<iostream>
- #include<string>
- #include<limits>
- #include<cctype>
- using namespace std;
- //Prototypes
- double readDouble(string errorMsg = "", int min = INT_MIN, int max = INT_MAX);
- int main()
- {
- double x;
- do {
- cout << " Enter a value: ";
- x = readDouble("test1 use default args");
- cout << " Enter a value: ";
- x = readDouble("test2 1.5,19.5", 1.5, 19.5);
- cout << " Enter a value: ";
- x = readDouble("test3 -2000.5678912,100.567", -2000.5678912, 100.567);
- cout << " Enter a value: ";
- x = readDouble("test4 -9999999,9999999", -9999999, 9999999);
- cout << " Enter a value: ";
- x = readDouble("test5 -929999999.5,929999999.5", -929999999.5, 929999999.5);
- cout << " Enter a value: ";
- x = readDouble("test6 -1,1234567890, default max", -1, 1234567890);
- cout << " Enter a value: ";
- x = readDouble("test7 -1234567890, 100", -1234567890, 100);
- cout << " Enter a value: ";
- x = readDouble("test8 -1234567890,1234567890", -1234567890, 1234567890);
- // etc.
- } while(true);
- system("pause");
- return 0;
- }
- double readDouble(string errorMsg, int min, int max)
- {
- double someDouble; // Stores each double entered.
- bool valid = false; // Loop control flag indeicating validdity of entry
- // initially assuming not valid.
- do
- {
- // Read an integer delimited by a whitespace character.
- cin >> someDouble;
- // Valid if within min to max range.
- valid = someDouble >= min && someDouble <= max;
- // Detect and remove invalid input.
- if (cin.fail() || !valid || !isspace(cin.peek()))
- {
- cout << "\nError! Invalid input.\n" << errorMsg << " must be a whole "
- << "number between " << min << " and " << max << ". \nTry Again: ";
- cin.clear(); // Clears the fail state.
- // Remove up to max number of chars in input stream or up to '\n'.
- cin.ignore(numeric_limits<streamsize>::max(), '\n');
- valid = false; // No valid entry has been read.
- }
- } while (!valid); // Loop again, prompting user to re-enter a valid integer.
- // When valid input received, remove from input stream up to 100 remaining
- // characters or until reaches the '\n' <ENTER> character.
- cin.ignore(100, '\n');
- return someDouble; // Returns a valid double to calling environment.
- }
Advertisement
Add Comment
Please, Sign In to add comment