简体   繁体   English

C ++ Switch语句

[英]C++ Switch Statement

Recently (yesterday hah) I started learning C++. 最近(昨天哈)我开始学习C ++。 I am trying to make a simple calculator to practice. 我正在尝试制作一个简单的计算器来练习。 I used a switch statement in order to call upon the correct method(or is it function.. don't know the nuances of c++...) within the class; 我使用了一个switch语句来调用类中正确的方法(或者它是函数......不知道c ++的细微差别......);

However, the code will not compile because I am using a string to define which case to use and also defining multiple classes to have the same result. 但是,代码将无法编译,因为我使用字符串来定义要使用的大小写,并定义多个类以获得相同的结果。

Here is the switch statement (I've only done addition to squash any bugs before I add the others): 这是switch语句(我在添加其他bug之前只添加了压缩任何错误):

switch(input){
        case 'A': case 'a': case 'add': case 'Add':
            cout << bo.addNum();
            break;
        default:
            cout << "Not addition";
            break;
    }

The error I'm getting is the following: 我得到的错误如下:

basic.cpp:41:2: error: statement requires expression of integer type ('string'
      (aka 'basic_string<char, char_traits<char>, allocator<char> >') invalid)
        switch(input){
        ^      ~~~~~
basic.cpp:42:28: warning: multi-character character constant [-Wmultichar]
                case 'A': case 'a': case 'add': case 'Add':
                                         ^
basic.cpp:42:40: warning: multi-character character constant [-Wmultichar]
                case 'A': case 'a': case 'add': case 'Add':
                                                     ^

Here is the code in its totality: 以下是其总体代码:

#include <iostream>
#include <cstdlib>
#include <string>

using namespace std;

class beckahClass{
public:
    void setNum(int num1, int num2){
        a = num1;
        b = num2;
    }
    int addNum(){
        return a + b;
    }
    int subNum(){
        return a - b;
    }
    int divNum(){
        return a / b;
    }
    int multNum(){
        return a * b;
    }
private:
    int a, b;
};

int main (void){
    beckahClass bo;
    string input;
    int a, b;

    cout << "Please specify the operation to preform by the following:\n A: add\nS: subtract\nM: Multiple\nD: divide\nEnter operation:  ";
    cin >> input;

    cout << "Enter the two nums you want to preform your operation on: ";
    cin >> a >> b;
    bo.setNum(a, b);

    switch(input){
        case 'A': case 'a': case 'add': case 'Add':
            cout << bo.addNum();
            break;
        default:
            cout << "Not addition";
            break;
    }   
    return 0;
}

I also realize there are probably more efficient ways to use logic; 我也意识到可能有更有效的方法来使用逻辑; because I'm just starting C++, I would greatly appreciate any critique. 因为我刚刚开始使用C ++,所以我非常感谢任何批评。 I had been looking up 'maps' before briefly and was wondering if this might be a good instance to use it in? 我之前一直在查看“地图”,并想知道这可能是一个很好的实例吗?

Thanks. 谢谢。

In C++ , the switch statement takes an int argument, and you are trying to use it with a string , which you can not do in C++ . C++switch语句采用int参数,并且您尝试将其与string一起使用,而这在C++无法实现的。

In this specific case, I'd argue that what you're trying to do with your switch is far to simple and an if else block would be better (plus it'd actually work with string ). 在这个特定的情况下,我认为你尝试用你的switch做的很简单, if else块会更好(加上它实际上用string )。

For example: 例如:

if(input == "A" || input == "a" || input == "add" || input == "Add") {
    cout << bo.addNum();
} else {
    cout << "Not addition";
}

Alternatively, as others have explained, you can switch on a char . 或者,正如其他人所解释的那样,您可以switch一个char As it turns out, you can access the individual characters of a string quite nicely. 事实证明,您可以很好地访问字符串的各个字符。 This method will have your switch statement work on the first character of the string you took as input . 此方法将使您的switch语句在您作为inputstring的第一个字符上工作。

switch(input[0]) {
    case 'A': case 'a':
        //stuff
        break;
    case 'S': case 's':
        //stuff
        break;
    //and so on
    default:
        //stuff
        break;
}

Just keep in mind that if you do it this way, you're going to enter case 'A': case 'a': whether the user types A , a , add , Add , addition , Addition , ADD , or Apples , or alphabet , or anything that starts with an a . 请记住,如果你做这种方式,你要进入case 'A': case 'a':是否在用户键入AaaddAddadditionAdditionADD ,或者Apples ,或者alphabet ,或任何以a开头的东西。

The reason is that C/C++ switch statement takes an int argument and do not support string as a type. 原因是C / C ++ switch语句采用int参数而不支持string作为类型。 Although it supports the notion of constant array. 虽然它支持常量数组的概念。 Also to mention that C/C++ switch statements are typically generated as branch tables. 另外要提到的是,C / C ++ switch语句通常作为分支表生成 and it is not easy to generate a branch table using a string style switch. 并且使用string样式开关生成分支表并不容易。

In C++ the switch statement takes int as the argument. 在C ++中,switch语句将int作为参数。

Why you cannot string in switch and getting the below error? 为什么你不能在开关中串起来并得到以下错误?

basic.cpp:42:28: warning: multi-character character constant [-Wmultichar]
                case 'A': case 'a': case 'add': case 'Add':
                                         ^
basic.cpp:42:40: warning: multi-character character constant [-Wmultichar]
                case 'A': case 'a': case 'add': case 'Add':

The reason is because to generate the code for switch the compiler must understand what it means for two values to be equal. 原因是因为要生成切换代码,编译器必须理解两个值相等意味着什么。 For int and enum, it is trivial and easy as they are constant values. 对于int和enum,它是微不足道的,因为它们是常量值。 But when it comes to string then it is difficult resulting in error. 但是当涉及到字符串时,很难导致错误。

welcome to the world of C++, hope you enjoy. 欢迎来到C ++世界,希望您喜欢。

Anyway let's talk about your problem. 无论如何,我们来谈谈你的问题。 Firstly, methods and functions are synonymous. 首先,方法和功能是同义词。

Secondly, the single quote is used around a single character and double quotes are used around a string. 其次,单引号用于单个字符,双引号用于字符串。 As in I have a string "Rabbiya" that consists of characters 'R','a','b','i','y' . 就像我有一个字符串"Rabbiya" ,由字符'R','a','b','i','y' Get it? 得到它? So you write "add" and 'a' like that in the code. 所以你在代码中写下"add"'a' Get it? 得到它?

Also in the switch statement, you are using two DIFFERENT data types to check the condition, one is a character and the other is a string. 同样在switch语句中,您使用两种不同的数据类型来检查条件,一种是字符,另一种是字符串。 "add" and "Add" are strings and 'a' and 'A' are chars. "add""Add"是字符串, 'a''A'是字符。 Which is wrong. 哪个错了。 Cases have the values that the argument of the switch statement can or may take. 案例具有switch语句的参数可以或可以采用的值。 And the argument will obviously be a variable of a particular type, we will get to that. 而论证显然是一个特定类型的变量,我们将达到这一点。

The data types of the CASES must be the same as that of the ARGUMENT of switch - statement. CASES的数据类型必须与switch - statement的ARGUMENT相同。 Here's one thing you can do, instead of keeping char or string , you ask the user to identify the operation they perform using a number instead. 这里有一两件事你可以做的,而不是保持一致, charstring ,你问用户识别操作他们进行使用,而不是数量。 Like 喜欢

int a = 0;
cout << Enter: 1 for Add\\n2 for Sub\\n3 for Div\\n4 for Sub: ";
cin >> a;

Then u use switch(a) statement with cases : case:1 , case:2 and so on. 然后你使用switch(a)语句与case: case:1case:2 ,依此类推。

Here it will be good to have a default case too so that if an invalid input is provided, it generates an error message. 这里最好有一个默认情况,以便在提供无效输入时,它会生成错误消息。

One more thing, in the class, you have two data members namely a and b . 还有一件事,在课堂上,你有两个数据成员,即ab You will need to initialize these too! 您还需要初始化这些! Otherwise you will get errors or garbage values depending on the compilers. 否则,您将获得错误或垃圾值,具体取决于编译器。 For this purpose, you write class constructors. 为此,您编写类构造函数。 What are constructors? 什么是构造函数? They help you initialize data members of a class object. 它们可以帮助您初始化类对象的数据成员。 For this purpose you should refer to this link: http://www.learncpp.com/cpp-tutorial/85-constructors/ 为此,您应该参考以下链接: http//www.learncpp.com/cpp-tutorial/85-constructors/

http://www.learncpp.com/ will help you a lot throughout your course! http://www.learncpp.com/将在整个课程中为您提供帮助!

string input; 字符串输入;

try changing it to 尝试将其更改为

char input 

As it was said C++ does not support using user-defined types (std::string is a user defined type) in the switch statement. 正如所说C ++不支持在switch语句中使用用户定义的类型(std :: string是用户定义的类型)。 It allows to use only integral types or enumerations. 它允许仅使用整数类型或枚举。 By the way the type char belongs to integral types. 顺便说一下char类型属于整数类型。 If you want to use strings in the switch statement then write your program in C#. 如果要在switch语句中使用字符串,请在C#中编写程序。

You can use any type c/c++ switch implementation . 您可以使用任何类型的c / c ++ 开关实现 Your code will be like this: 你的代码将是这样的:

SWITCH(input)
    CASE("A") FALL
    CASE("a") FALL
    CASE("Add") FALL
    CASE("add") FALL
        cout << bo.addNum();
        BREAK
    DEFAULT
        cout << "Not addition";
END

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM