使用开关比较字符

character comparison using switch

我正在逐个字符地比较字符串。

这是我的代码中导致问题的部分:

switch(line[1]) {
case 'u':
    switch(line[2]) {
    case 't':
        switch(line[3]) {
        case 't':
            switch(line[4]) {
            case 'o':
                switch(line[5]) {
                case 'n':
                    switch(line[6]) {
                    case 's':
                        printf("buttons\n");
                    case ' ':
                        printf("not buttons\n");
                    break;
                    }
                break;
                } 
            break;
            }
        break;
        }
    break;
    }
}

对于line[6],如果存在s字符,则应打印出"buttons",如果存在space,则应打印出"not buttons"

如果我的配置文件包含:

buttons 13
button  3
buttons 3

我得到:

buttons
not buttons
buttons
not buttons

如果我有:

buttons 3

我得到:

buttons
not buttons

我得到每个按钮条目的 "buttons" 和 "not buttons" 而 "button 3" 条目

什么也得不到

谢谢

当有buttons时,你总是会得到not buttons,因为你在case 's'之后没有中断。因此当line[6]是[=时它不会停止14=]。 您使用所有这些嵌套开关只是为了比较 string.Better 使用 strcmp 来检查它是 buttons 还是 button.

不要使嵌套开关复杂化,而是使用这个

FILE * fi;    // input file handle
char line[9], c;

while (feof(fi) == 0) {
    // Read only required chars
    fgets(line, 8, fi);
    line[8] = '[=10=]';
    while ((c = getc(fi)) != '\n' && c != EOF);

    // Simplified comparison
    if (strncmp(line, "button", 6) == 0) {
        if (line[6] == 's') printf("buttons\n");
        else if (line[6] == ' ') printf("not buttons\n");
    }
}

这是一个更简单、更清晰的代码版本:

if (strncmp(line, "button", 6)==0)
{
  if (line[6]=='s')
  printf("buttons");
  else printf("button");
}