【问题标题】:C++ (Type error in Switch statement) [duplicate]C ++(Switch语句中的类型错误)[重复]
【发布时间】:2017-03-19 02:57:46
【问题描述】:

好的,所以当我尝试根据用户的输入打印某些内容时出现错误。很标准的东西,对吧?因此,如果程序正常运行,用户将输入六个单词或短语,这些单词或短语将存储在名为 PhrasesAndWords 的字符串中。然后,将通过创建一个while循环,使用计数器作为switch语句中的索引来测试数组的每个部分。好吧,显然,这不起作用,因为它不是常量表达式或 constexpr。但是,该变量不能是常量表达式,因为这会导致无限循环。顺便说一句,这是错误:

C:\Users\henry\Desktop\NotTheActualPathForThisProject\main.cpp|34|错误:开关量不是整数|

这是我写的代码(不过我已经去掉了不相关的变量等):

int main() {

string phrasesAndWords[6];

cin >> phrasesAndWords[0] >> phrasesAndWords[1] >> phrasesAndWords[2] >> phrasesAndWords[3] >> phrasesAndWords[4] >> phrasesAndWords[5]; // Recieve input

int counter = 0;

    while (counter < 6) {
    switch(phrasesAndWords[counter]) {

        case "RandomString":
            print("That sure was quite random. \n")
        default:
            print("I don't understaahnd... \n")
    };
    counter++;
};

};

【问题讨论】:

  • switch quantity not an integer。非常强烈的提示,您不能在 C++ 中使用字符串 switch...
  • @John3136 也许他来自 Java 背景 :-)
  • 将其设为向量改为短语,并使用短语.push_back();
  • 你可以找到你的答案here

标签: c++ while-loop switch-statement


【解决方案1】:

switch 语句中使用的表达式必须是整数或枚举类型,或者是类类型,其中类具有单个转换函数到整数或枚举类型。

【讨论】:

    【解决方案2】:

    C++ 中的 Switch 不适用于字符串。考虑用整数映射预期的情况。

    【讨论】:

    • 我不知道。谢谢你告诉我:D
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-21
    • 1970-01-01
    • 2016-07-12
    • 1970-01-01
    相关资源
    最近更新 更多