如何在 switch 语句中使用 cin "as a parameter"

How to use cin "as a parameter" in a switch statement

我希望能够使用 cin 创建一个 switch 语句,而不必创建一个变量来存储输入的值。例如:

switch(cin){
case 1: std::cout << "Hello World";
break;
default:
break;
}

我希望能够使用 cin 创建 switch 语句? 不,你不能,因为 switch 只需要 integral 个数量,但是 cin 是 class 的对象。来自 n4296 第 6.4 节

switch ( condition ) statement

The value of a condition that is an initialized declaration in a switch statement is the value of the declared variable if it has integral or enumeration type, or of that variable implicitly converted to integral or enumeration type otherwise. The value of a condition that is an expression is the value of the expression, contextually converted to bool for statements other than switch; if that conversion is ill-formed, the program is ill-formed.

switch(cin) 由于我上面提到的原因导致错误,但您可以使用 returns integer 的任何方法,例如 cin.get(),例如

switch(std::cin.get()) {
   /*... */
}