adamjoliver

Untitled

Apr 4th, 2016
148
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.28 KB | None | 0 0
  1.  
  2. #include<iostream> //Preprocessor commands
  3. #include<string>
  4. #include<cstdlib>
  5. using namespace std; //Using namespace library
  6.  
  7. int input_val(); //Function prototype
  8.  
  9. int main() //Driver function header
  10. {
  11. char ch;
  12.  
  13. cout<<" "<<input_val()<<" is a valid integer entry."<<endl<<endl;
  14.  
  15. cout<<"Enter 'e' to exit... ";
  16. cin>>ch;
  17.  
  18. return 0;
  19. }
  20.  
  21. int input_val()
  22. {
  23. string text;
  24. int n = 99, i, x; //Defining n, i, and x
  25.  
  26. while (n != 0) //As long as n doesn't equal 0, do the following...
  27. {
  28. try
  29. {
  30. //Obtain user input
  31. cout<<"Please enter an integer ('e' to exit): ";
  32. getline(cin,text);
  33.  
  34.  
  35. if (text == "e") throw 3; //If user inputs the letter e, exit the program
  36.  
  37. if (text.length() == 0) throw 1; //Making sure it has a length greater then 0
  38.  
  39. if (text[0] == '+');
  40.  
  41. for (i = 0; i <text.length(); i++) if (!isdigit(text.at(i))) throw 2; //Looking for more digits or a decimal point
  42.  
  43. atoi(text.c_str());
  44.  
  45. if (text > "255") throw 4; //Making sure the number is not greater then 255
  46.  
  47. if (text < "0") throw 5; //Making sure the user didn't input a negative
  48.  
  49. //If all the tests go well, move on with the program
  50. n = 0;
  51. }
  52. catch (int e)
  53. {
  54. if (e == 1) cout<<"\n No input was entered!"<<endl<<" Try again... "; //Telling the user what went wrong
  55. if (e == 2) cout<<"\n You either entered a letter or a symbol that is not a number."<<endl<<" Try again... ";
  56. if (e == 3) exit(0);
  57. if (e == 4) cout<<"\n You put in a number greater than 255."<<endl<<" Try again... ";
  58. if (e == 5) cout<<"\n You put in a negative number! No negatives!"<<endl<<" Try again... ";
  59.  
  60.  
  61. n = 99; //Resetting the setinel so the while loop can run again
  62. }
  63. }
  64. //Converting C string to an integer with atoi
  65. return atoi(text.c_str());
  66. }
Advertisement
Add Comment
Please, Sign In to add comment