Request Short Link
C++ 98
C++ 11
C++ 14
C++ 17
C++ 20
C++ 23
C++ 2c
for-loops as while-loops
array subscription
Show all implicit casts
Show all template parameters of a CallExpr
Use libc++
Transform std::initializer_list
Show noexcept internals
Show padding information
Show coroutine transformation
Show C++ to C transformation
Show object lifetime
Default
15
18
20
22
26
More
GitHub
Patreon
Issues
About
Policies
Examples
C++ Insights @ YouTube
Settings
Version
Workshop: Safe and Efficient C++ for Embedded Environments
×
Made by
Andreas Fertig
Powered by
Flask
and
CodeMirror
Source:
#include <iostream> #include <limits> int main() { // I'd advise against it, but you could at least do: using std::cout; using std::cin; // instead of using namespace std, which I assume you did // OR, again, not recommended but at least limit the scope of // using namespace std; int choice; while (true){ cout << "Enter choice: \n"; // `std::cin` (converts to `bool` indicating errors or lack thereof) - https://en.cppreference.com/w/cpp/io/basic_ios/operator_bool // this is the concise version but you can also split it // it works because cin returns a reference to self when doing operator >> - also called insertion or put - https://en.cppreference.com/w/cpp/io/basic_istream/operator_gtgt2 if(!(cin >> choice)) { cout << "invalid input! please enter a number\n"; // clear the error state of this input stream // docs: https://en.cppreference.com/w/cpp/io/basic_ios/clear cin.clear(); // ignore all the input that was passed by the user until a certain max limit // https://en.cppreference.com/w/cpp/io/basic_istream/ignore cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // here you can: // 1) continue the loop and re-ask for input // continue; // 2) get out of the loop and end the program (seems that that's what you want to do break; } switch(choice){ case 1: cout << "you picked 1\n"; break; case 2: cout << "you picked 2\n"; break; default: cout << "invalid choice\n"; break; } } }
Insight:
Console: