Since you managed to get this program to compile I can only assume that repeat_transaction
was specified as a char
and not a std::string
.
When you use cin
to get a character it only gets one character but it doesn't flush the buffer. I believe you understand this issue since you wrote This was before I attempted to use static_cast to force the truncation of the user input. . You can attempt to use cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
instead of static_cast<char>(repeat_transaction);
after each call to cin >> repeat_transaction;
. There are downsides to this. If you enter 'mn' it will work as expected. It reads the m
which is not y
or n
and then flushes the extra characters until it finds end of line \n
. If you do nm
, n
will match and the m
will be thrown away. So in that case it will accept nm
as valid and exit the loop.
There are other ways that may be easier and give you the effect closer to what you are looking for. Instead of reading a character at a time you can read an entire line into a string using getline
(See the C++ documentation for more information). You can then check if the length of the string is not equal to 1
character. If it's not length 1
then it is invalid input. If it is 1
then you want to check for y
and n
. Although basic (and not overly complex) this code would do a reasonable job:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string repeat_transaction;
cout << "Would you like to make another transaction? (y/n)" << endl;
getline(cin, repeat_transaction);
while (repeat_transaction.length() != 1 || (repeat_transaction != "y" && repeat_transaction != "n"))
{
cout << "Invalid selection: Please enter y or n";
getline(cin, repeat_transaction);
}
return 0;
}
I said reasonable job since one deficiency you might see is that you want to trim white spaces from the beginning and end. If someone enters n
or y
with a space
or tab
in front it will be seen as invalid (whitespace at the end would be similar). This may not be an issue for you, but I thought I would mention it.
On a final note, you may have noticed I used using namespace std;
. I did so to match what was in the original question. However, this is normally considered bad practice and should be avoided. These StackOverflow answers try to explain the issues. It is better to not do it and prepend all standard library references with std::
. For example string
would be std::string
, cin
would be std::cin
etc.