【问题标题】:How to use cin "as a parameter" in a switch statement [duplicate]如何在switch语句中使用cin“作为参数”[重复]
【发布时间】:2018-04-21 12:43:03
【问题描述】:

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

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

【问题讨论】:

  • 你可以使用:switch ( std::cin.get() ) { 然后case 49:case '1':
  • 嗯:switch([]{int i; std::cin &gt;&gt; i; return i;}()){ ...
  • @RichardCritten 我喜欢那个^_^
  • @RichardCritten 使用 C++17 更容易:switch (int n; std::cin &gt;&gt; n, n) { ...

标签: c++ switch-statement cin


【解决方案1】:

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

switch(条件)语句

condition 的值,它是 switch 语句是声明变量的值,如果它有 integralenumeration 类型,或该变量的隐式转换 否则为整数或枚举类型。条件值 that is an expression 是表达式的值,根据上下文 对于 switch 以外的语句,转换为 bool;如果那个转换 是非良构的,程序是非良构的。

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

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

【讨论】:

    猜你喜欢
    • 2012-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-23
    • 2015-12-26
    • 1970-01-01
    • 2014-01-06
    • 1970-01-01
    相关资源
    最近更新 更多