如何在C++中使用switch case比较字符串

che*_*263 1 c++ string parsing switch-statement

我是C++的新手.

我必须做一个解析器.选择"34 + 5-(9*8)"之类的输入并将其插入二叉树.我的想法是比较字符串中的每个字符并确定字符是数字还是simbol(+, - ,*,/等)并将其插入队列以使用后缀表示法然后将其插入二叉树

我想要的是要求用户输入字符串,将字符串拆分为字符然后进行比较

就像是

#include <iostream>
#include  <string>
using namespace std;

string cadena;
string numero;
int i;

int main(){

    cout<< "Type String";
    cin>> cadena;
    for (i=0; i<cadena.length(); i++){
        switch(cadena[i]{
            case "0":
            case "1":
            case "2":
            ...
            case "9":
                numero+=cadena[i];
        }
        cout << numero<<endl;
        numero="";
    }
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

但编译器抱怨我无法将当前的char(cadena[i])与我的字符串("0")进行比较.

谁能让我知道该怎么做?

我已经尝试过使用char std:string,阅读其他问题等.

tem*_*def 8

你的switch语句中的case标签现在是字符串,但是你正在解析的字符串的每个单独的部分都是一个char.尝试将案例标签中的双引号更改为单引号.例如:

switch (cadena[i]) {
    case '0':

    /* ... */
}
Run Code Online (Sandbox Code Playgroud)

更一般地,case标签中的常量必须是整数数字常量,如int,char,short等.您不能在其中放置其他类型的值.

也就是说,您可能希望查看isdigit标题中的函数,该函数<cctype>直接测试字符是否为数字.

希望这可以帮助!


Jam*_*lin 6

代替

    case "0":
    case "1":
Run Code Online (Sandbox Code Playgroud)

使用

    case '0':
    case '1':
Run Code Online (Sandbox Code Playgroud)

(当然还有其他人)