Hello mrtammy2008,
When I look over the responses I feel as you do not have a good understanding of
cin >> amount_input;
.
To start with
cin >> amount_input;
also known as formatted input, and my experience has been it works best when the variable is defined as a numeric variable, tells "cin" to expect a number. So, when you key in 2 enter everything is fine. When you input something like "2w" it will extract the "2" into the numeric variable and leave the "w" and new line in the input buffer. This also means it will extract the number until it finds something that is not a number like "w", a white space or a new line.
That is why when you enter "2w" "cin" does not fail because it is able to put a number into the variable until it finds something that is not a number.
The while loop works when you enter something that is not a number. Which means that you enter a letter when the formatted input is expecting a number.
Also I would use
while (!std::cin)
. Bear with me here because I do not use
using namespace std;
. This is a broader approach for checking the status of "std::cin". This is checking the status if the "good" bit which will be changed when any of the other state bits are set.
What is inside the while loop is fine.
The try/catch example from
lastchance is good. A little more involved than I am use to. But the line
i = stoi( test, &pos );
is much the same as formatted input. It will extract a number from a string until it finds something that is not a number like a letter, white space or a new line. If I understand correctly a period in a floating point number will read the number, but a period after a number is considered non numeric.
My use of the try/catch is a bit more simple.
1 2 3 4 5 6 7 8
|
try
{
i = stoi(test);
}
catch (const std::exception& e)
{
std::cout << "\n " << e.what() << '\n' << std::endl;
}
|
Like
lastchance's example what is in the () will catch any exception with the difference being that you can see what the exception is. With a try/catch you can have multiple catch blocks each tailored to the exception thrown. First you need to know what exception has been thrown.
In the past I have used this code and it has worked well for what I was doing. For the future I will have to work through
lastchance's code to better understand how it works.
Should I have something wrong, someone let me know.
Hope that helps,
Andy