Pastebin launched a little side project called HostCabi.net, check it out ;-)Don't like ads? PRO users don't see any ads ;-)
Guest

Input Checking

By: a guest on Feb 2nd, 2013  |  syntax: C++  |  size: 1.23 KB  |  hits: 9  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. #include <iostream>
  2. #include <string>
  3.  
  4. using namespace std;
  5.  
  6. void getNoColors(int *no_colors);
  7.  
  8. int main(void)
  9. {
  10.         int noColors = 0;
  11.  
  12.         getNoColors(&noColors);
  13.  
  14.         return 0;
  15. }
  16.  
  17. void getNoColors(int *no_colors)
  18. {
  19.         bool invalid = true;
  20.         long int cGuard = 0;
  21.         string iGuard = "";
  22.  
  23.         //Do-While to continuously loop until input is valid
  24.         do
  25.         {
  26.                 /* Don't just cin >> *no_colors. If the user enters a non-numeric character,
  27.                    your input will never stop looping with an error (your solution would not
  28.                    face this particular problem, as it doesn't loop on an input error).
  29.  
  30.                    Last cin.get() is to remove newline from stream
  31.                 */
  32.                 cout << "Enter the number of colors to display (Between 2 and 5 inclusively): ";
  33.                 cin >> iGuard;
  34.                 cin.get();
  35.                
  36.                 //Convert string input; safe conversion is to long int.
  37.                 //We'll check that it doesn't pass int range after.
  38.                 cGuard = atoi(iGuard.c_str());
  39.                 *no_colors = (int) cGuard;
  40.  
  41.                 //Remember, C++ does short-circuit checking, so if cGuard is out of range,
  42.                 //we'll never even check if *no_colors is in range.
  43.                 invalid = cGuard > INT_MAX || cGuard < INT_MIN || *no_colors < 2 || *no_colors > 5;
  44.  
  45.                 if(invalid)
  46.                         cout << "ERROR: Invalid input.\n\n";
  47.  
  48.         }while(invalid);
  49. }