Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<iostream> //Preprocessor commands
- #include<string>
- #include<cstdlib>
- using namespace std; //Using namespace library
- int input_val(); //Function prototype
- int main() //Driver function header
- {
- char ch;
- cout<<" "<<input_val()<<" is a valid integer entry."<<endl<<endl;
- cout<<"Enter 'e' to exit... ";
- cin>>ch;
- return 0;
- }
- int input_val()
- {
- string text;
- int n = 99, i, x; //Defining n, i, and x
- while (n != 0) //As long as n doesn't equal 0, do the following...
- {
- try
- {
- //Obtain user input
- cout<<"Please enter an integer ('e' to exit): ";
- getline(cin,text);
- if (text == "e") throw 3; //If user inputs the letter e, exit the program
- if (text.length() == 0) throw 1; //Making sure it has a length greater then 0
- if (text[0] == '+');
- for (i = 0; i <text.length(); i++) if (!isdigit(text.at(i))) throw 2; //Looking for more digits or a decimal point
- atoi(text.c_str());
- if (text > "255") throw 4; //Making sure the number is not greater then 255
- if (text < "0") throw 5; //Making sure the user didn't input a negative
- //If all the tests go well, move on with the program
- n = 0;
- }
- catch (int e)
- {
- if (e == 1) cout<<"\n No input was entered!"<<endl<<" Try again... "; //Telling the user what went wrong
- if (e == 2) cout<<"\n You either entered a letter or a symbol that is not a number."<<endl<<" Try again... ";
- if (e == 3) exit(0);
- if (e == 4) cout<<"\n You put in a number greater than 255."<<endl<<" Try again... ";
- if (e == 5) cout<<"\n You put in a negative number! No negatives!"<<endl<<" Try again... ";
- n = 99; //Resetting the setinel so the while loop can run again
- }
- }
- //Converting C string to an integer with atoi
- return atoi(text.c_str());
- }
Advertisement
Add Comment
Please, Sign In to add comment