Extra credit options: Handling non-numeric input where a number is expected Meet
ID: 3759701 • Letter: E
Question
Extra credit options: Handling non-numeric input where a number is expected
Meeting the above requirements will allow you to earn a maximum of 80/80 for this assignment. If you like, you can choose to modify your program to meet either or both of the following additional requirements, for the specified number of extra points giving a maximum of 20 additional points, allowing a total up to 100/80. The purpose of these options is for the program to be able to detect non-numeric input where it is expecting a number, and reprompt for input until it obtains a number (with or without a fraction, as expected).
(10 points) Modify your program so that where the user’s choice from the menu is read, the two lines that would have been something like:
are replaced by a function call like:
choice = get_int("Enter the number of your choice: "); Add the get int function to your program. It must have the prototype:
and must work as described below.
(10 points) Modify your program so that where it reads numeric data entered by the user into variables of type double, instead of using cin >> directly into the variable, the input is read through a call to get double. For example, lines like:
could be replaced by something like:
And lines like:
could be replaced by ones like:
factor = get_double("Enter the scale factor: ");
Add the get double function to your program. It must have the prototype:
and must work as described below.
• If you include either of the functions get int or get double in your program, they must work as follows:
– Display the parameter prompt to the user.
– Read in the user’s response as a C-string, and convert it to the return type of the function using a
conversion function from <cstdlib>. (Use strtol for get int, and strtod for get double.)
– Check whether or not the conversion from a string to a number worked successfully: If successful, the converted number must be returned by the function; Otherwise, the user must be reprompted to enter a number until they give a valid response (i.e. one which successfully converts to a number).
• A sample run showing behavior of the two functions get int and get double would look like:
Explanation / Answer
int total(vector<int> v)
{ int total = 0;
for (int i = 0; i < v.size(); i++)
total += v[i];
return total;
}
void add_word(vector<string>& vs, string s) // the procedure modifies the vector,
// so we pass by reference (without const)
{ for (int i = 0; i < vs.size(); i++ )
if (s == vs[i]) return; // don't add the word as it's
// already in the vector
vs.push_back(s);
}
string s;
vector<string> v;
while (cin >> s)
add_word(v,s);
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.