21xrx.com
2024-09-19 09:35:43 Thursday
登录
文章检索 我的文章 写文章
如何在C++中使用字符串作为Switch语句的条件
2023-07-04 23:06:30 深夜i     --     --
C++ 字符串 Switch语句 条件 使用

字符串是计算机中常用的数据类型之一,它在计算机程序的开发中扮演着重要的角色。在C++程序中,开发者可能会需要使用字符串作为switch语句的条件进行分支控制。本篇文章将会简要介绍如何在C++中使用字符串作为Switch语句的条件。

在C++中,如果想要使用字符串作为Switch语句的条件,需要首先使用std命名空间下的string类进行定义。


#include <iostream>

#include <string>

using namespace std;

int main()

{

  string input;

  cout << "请输入一个字符串: ";

  cin >> input;

  switch (input)

  

    case "apple":

      cout << "您输入了苹果" << endl;

      break;

    case "banana":

      cout << "您输入了香蕉" << endl;

      break;

    case "orange":

      cout << "您输入了橙子" << endl;

      break;

    default:

      cout << "未知的水果" << endl;

      break;

  

  return 0;

}

通过使用string类,我们可以在Switch语句中使用字符串作为条件进行分支控制。注意,Switch语句中使用的字符串应该使用双引号(" ")括起来,表示这是一个字符常量。

在进行switch案例判断的时候,我们会发现程序编译不过去,并且报错了。一旦测试的字符串很多,这个方法自然也就不适用了。正确的方法是使用常量Hash,先把每个字符串算出它的Hash值并存起来,然后在switch语句中根据输入的字符串计算出它的Hash值并与预存储的Hash值进行对比即可。


#include <iostream>

#include <string>

#include <unordered_map>

using namespace std;

int main()

{

  unordered_map<string, int> dict = { 1, "banana", "pear" };

  string input;

  cout << "请输入一个字符串:";

  cin >> input;

  auto it = dict.find(input);

  if (it == dict.end())

  

    cout << "未知的水果" << endl;

  

  else

  {

    switch (it->second)

    

      case 1:

        cout << "您输入了苹果" << endl;

        break;

      case 2:

        cout << "您输入了香蕉" << endl;

        break;

      case 3:

        cout << "您输入了梨子" << endl;

        break;

      default:

        cout << "未知的水果" << endl;

        break;

    

  }

  return 0;

}

通过使用unordered_map(哈希表),我们可以先将字符串与预设的Hash值进行映射形成键值对的存储关系,然后再使用Switch语句根据预设的Hash值进行分支控制。

总结:

在C++开发中,使用字符串作为Switch语句的条件进行分支控制需要注意一些细节问题。通过使用string类或者unordered_map哈希表,我们可以实现字符串作为Switch语句的条件,并且可以避免错误的发生。掌握正确的方法将会对C++开发的效率和优化有很大的提升。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复