I\'m taking an intro to C++, and I\'m using VStudio 2013 on Win7. I try to avoid the wrong data input from my menus, and it\'s working in all of them except this one.
<
Code that Limits Potential Side Effects
In my testing, #undef max
does not seem to need to be done before any #include
s.
You might want to limit potential side effects in general by first pushing the max
macro, then undefining it, then popping it off after using max from
like this (only tested on Windows/Visual Studio 2019):
// stuff ...
#pragma push_macro("max")
#undef max
std::cin.ignore(std::numeric_limits::max(), '\n');
#pragma pop_macro("max")
// more stuff ...
See the Microsoft Docs: push_macro and pop_macro
Put it in a function to make it DRY:
void CinIgnore() {
#pragma push_macro("max")
#undef max
std::cin.ignore(std::numeric_limits::max(), '\n');
#pragma pop_macro("max")
}
Add std::cin.clear
to make a CinReset
function:
void CinReset() {
std::cin.clear();
#pragma push_macro("max")
#undef max
std::cin.ignore(std::numeric_limits::max(), '\n');
#pragma pop_macro("max")
}
Additional information: this cppreference.com article on ignore
has a good example of how to use clear
and ignore
, along with state flags, effectively, but does not have the necessary fix for Windows/Visual Studio noted above.
NOTE: The above, though standard, does not work well with the user interactively inputting EOF (ctrl-z
- Windows using Visual Studio). I have written a IStreamUtils
class that includes a Reset method that is more robust. I will add a link to an article about that here later.