Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <string>
- using namespace std;
- void getNoColors(int *no_colors);
- int main(void)
- {
- int noColors = 0;
- getNoColors(&noColors);
- return 0;
- }
- void getNoColors(int *no_colors)
- {
- bool invalid = true;
- long int cGuard = 0;
- string iGuard = "";
- //Do-While to continuously loop until input is valid
- do
- {
- /* Don't just cin >> *no_colors. If the user enters a non-numeric character,
- your input will never stop looping with an error (your solution would not
- face this particular problem, as it doesn't loop on an input error).
- Last cin.get() is to remove newline from stream
- */
- cout << "Enter the number of colors to display (Between 2 and 5 inclusively): ";
- cin >> iGuard;
- cin.get();
- //Convert string input; safe conversion is to long int.
- //We'll check that it doesn't pass int range after.
- cGuard = atoi(iGuard.c_str());
- *no_colors = (int) cGuard;
- //Remember, C++ does short-circuit checking, so if cGuard is out of range,
- //we'll never even check if *no_colors is in range.
- invalid = cGuard > INT_MAX || cGuard < INT_MIN || *no_colors < 2 || *no_colors > 5;
- if(invalid)
- cout << "ERROR: Invalid input.\n\n";
- }while(invalid);
- }
Advertisement
Add Comment
Please, Sign In to add comment