C++(Switch 语句中的类型错误)

标签 c++ while-loop switch-statement

<分区>

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

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

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

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++;
};

};

最佳答案

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

关于C++(Switch 语句中的类型错误),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40436835/

相关文章:

swift - 按下按钮后使用 case 语句检查值的状态

c++ - 将包含/库目录和链接器参数传播到解决方案中的所有项目?

C++ move 语义和异常

c++ - 添加到指针 vector 时出错

谁能告诉我为什么这个无限的 while 循环不能正常工作?

c# - 将 MySQL 中的数据库更新为 LightSwitch 中的 SQL 服务器

c++ - C++ 是否有办法忽略函数的异常?

C# - 循环 foreach 直到 true

php 循环 - while 或 do while?

java - 对于 Android 事件,为什么 switch 语句比 if-else 链更常见?