【问题标题】:How can I write a switch statement with strings in C++? [duplicate]如何在 C++ 中编写带有字符串的 switch 语句? [复制]
【发布时间】:2023-03-15 11:35:01
【问题描述】:

我正在开发一个关于 Dev-C++ 的小项目。我正在尝试制作一个机器人来问你一些问题,但我不能使用带有字符串的 switch 语句。每次我尝试这样做时都会显示错误!我还尝试将 srings 更改为普通的 int 变量,但是当我回答第一个问题后代码立即运行时!有谁知道如何解决这些情况?

这是我的代码:

// #include "stdafx";

#include <iostream>
#include <string>
#include <stdio.h>
#include <string.h>

using namespace std;

int main()
{
    string comida;
    string nome;
    string idade;
    string pais;

    cout << "Ola, o meu nome e Aleksandar. Qual e o teu nome?" << endl; //Ask for nome
    cin >> nome; //Recieve variable nome

    cout << "Es de que pais, " << nome << "?" << endl; //Ask for pais
    cin >> pais; //Receive pais
    cout << pais << " e um pais bonito. " << "Eu sou de Portugal!" << endl; 

    cout << "Quantos anos tens " << nome << "?" << endl; //Ask for idade
    cin >> idade; //Receive variable idade

    switch (idade) {
       case 21:
          cout << "O meu irmao tambem tem 21 anos!" << endl;
          break;
    }
    cout << "Eu tenho 28" << endl;

    cout << "Qual e a tua comida preferida?" << endl; //Ask for comida
    cin >> comida; //Receive variable comida

    cout << "Tambem gosto muito de " << comida << ". Mas gosto mesmo e de Vatruchka!" << endl;
    cout << "Xau " << nome << "!" << endl;
}

【问题讨论】:

  • 为什么要使用一个简单的if 的开关呢?
  • 简短回答:你不能。 C++ 开关仅适用于整数 (int, char, ecc.) 常量。您可能需要考虑std::map&lt;string, std::function&lt;void()&gt;&gt;
  • 为什么你的缩进到处都是?
  • 投了反对票,因为人们应该先搜索(这个问题已经经常被回答)并且代码包含很多噪音——非英语的东西,而且通常有很多没有太多可做的代码做这个问题。

标签: c++


【解决方案1】:

一个 switch 在非整数时将无法编译(即字符串、浮点数、布尔值、向量等......)数据类型分配给开关的case: 语句。此外,分配给case: 语句的值必须是const。

换句话说:

开关必须使用“常量整数数据类型”(即'enum'、'int'、'char'等......),并且不能实现然而,字符串作为条件语句;这与说不能在条件语句中使用字符串不同,它们非常可能是 & 通常是 - 见下面的示例:


    std::string s;
    std::cin >> s;

    if (s == "Yes")
    {
       std::cout << "You said yes!" << std::endl;
    } 
    else if (s == "No")
    {
       std::cout << "You said no?"  << std::endl;
    }
    else 
    {
       std::cout << "You said something I don't understand"  << std::endl;
    }
所以要完成这个答案,您可以看到使用if/else 块的switch 语句可以实现相同的效果。它可能适合您的情况,也可能不适合您的情况,但这就是 C++ 和 switch 语句的工作方式,所以您坚持使用它 — 喜欢或不喜欢...

【讨论】:

  • 在实践中,大多数时候我需要“切换”字符串,我发现指向函数或多态函数对象的指针的映射是最佳解决方案。 (大多数时候。有一些例外情况我链接了if...else if...。)
  • 当然,但这可能不是 OP 在这种特殊情况下想要的讨论级别。
【解决方案2】:

如果字符串包含数字,switch(std::stoi(idade)) 将起作用。但如果 idade 包含其他内容,这将不起作用。

【讨论】:

  • 当然,这意味着你必须在某处有一个try 块。
  • @Xiao:这里没有安全问题。有一个隐含的default: break。
  • @Xiao:是的,switch 就是这样工作的。您正在编写 C++,而不是汇编。它远没有你想象的那么接近金属!
  • @Xiao:是的,它并没有说“但是可能会执行一些恰好在您的台式计算机内存中的随机代码”。 C++ 是一种抽象。它比你想象的要安全得多。对于一个有效的、定义良好的程序,它永远不会导致任意代码段被执行。我不能引用标准中确保这一点的部分,因为它遍布各处。这是与生俱来的。
  • @Xiao:从汇编的角度来看,“用作下一条指令的索引”无论如何都没有意义。考虑case 0:!
【解决方案3】:

您不能使用字符串 — switch 仅适用于整数 case 类型(即整数和枚举)。

你可以改用这样的东西:

if (idade == "21") { cout << "...\n"; }
else if (idade == "something else") { cout << "...\n"; }

您描述当您更改为使用整数时,代码会同时运行。您可能忘记在每个 case 子句中包含 break。

【讨论】:

    【解决方案4】:

    如果您有一组您期望的不同字符串,那么您可以设置一个枚举和一个映射(我在这里松散地使用映射这个词 - 我不是指 C++ 中的实际映射,尽管我知道它是可以用它做类似的事情)

    用它把输入变成一个枚举,然后你可以在枚举上运行一个开关

    例如

    enum class ANSWER
    {
        ANSWER_1,
        ANSWER_2
    };
    
    class AnswerMap    \\set up this class like a singleton
    {
        std::vector<std::pair<std::string, ANSWER>> _answer_map = {
            std::make_pair("Answer 1 string", ANSWER::ANSWER_1),
            std::make_pair("Answer 2 string", ANSWER::ANSWER_2)
        }
    
        std::string String(ANSWER answer);    \\have this function loop through this->_answer_map until finding the pair with the second item as the given enum and return the corresponding string
    
        ANSWER Enum(std::string answer);    \\have this function do the same as this->String but find the pair where the string matches and then return the corresponding enum
    }
    

    【讨论】:

    • 这似乎比 map 更复杂和更慢,原因不明
    • 当我不得不制定解决方案并且没有时间花时间学习如何使用地图时,我使用了它。它速度较慢,但​​不是我的应用程序的瓶颈,所以没关系
    猜你喜欢
    • 1970-01-01
    • 2012-10-24
    • 1970-01-01
    • 1970-01-01
    • 2018-06-08
    • 2015-12-24
    • 1970-01-01
    • 2016-12-12
    • 2020-12-06
    相关资源
    最近更新 更多