繁体   English   中英

C开关语句如何正确使用

[英]How to properly use C switch statement

我有一个代码片段,我用它来学习一些 C

char* input( char *s ){
    scanf("%[^\n]%*c",s);
    return s;
}
void main()
{
    printf("Welcome to a string input/output example written in C! \n");
    printf("Type e to exit \n");
    printf(" \n");  
    while (0 == 0){ 
        printf("> ");
        char str[100];
        input( str );
        //All off this code works perfectly until the switch statement, which apparently cannot recognized the 'e' case:
        switch(str){
            case 'e'    :   break;
            default     :   printf("Your string is: %s \n", str);           
        }

    }
}

但是,当此代码运行时,它会很好地返回字符串,但是在 switch 语句期间它默认为默认值,即使“str”的值为“e”,它也会返回:

你的字符串是:e

而不是退出。 请帮助这是很奇怪的..

您不能将 C 中的开关与字符串一起使用。 您现在正在做的是使用指向开关中数组 str 中第一个字符的指针。 这就是为什么总是转到默认部分。 做你想做的事的一个好方法是使用 strcmp: int strcmp(const char *str1, const char *str2); 如果返回值 < 0 则表示 str1 小于 str2。

如果返回值 > 0 则表示 str2 小于 str1。

如果返回值 = 0,则表示 str1 等于 str2。

char str2[]="e";
if(strcmp(str, str2))
    printf("Your string is: %s \n", str);
else
    break;

也不要使用 while(0==0),改用 while(1)

你不能切换字符串。 您可以使用if... else if代替。

while (1){ 
        printf("> ");
        char str[100];
        input( str );
        if(strcmp(str, "e") == 0){ // type e to exit
                break;

        } else if (strcmp(str, "abc") == 0) { // if you type abc
            // do something

        } else if (strcmp(str, "def") == 0) { // if you type def
            // do something

        } else { // it's a mimic of default in switch statement.
            printf("Your string is: %s \n", str);
        }

    }

使用strcmp比较字符串。 在您的代码中'e'是字符,而不是字符串。 你必须使用"而不是'

在此处查看更多信息在 C 中打开字符串的最佳方式

如果您仍然想要一个switch ,请阅读如何为字符串切换和大小写?

switch 内的 break 语句退出switch语句。 如果开关在循环内,它不会退出循环。 只是 switch 语句。

太糟糕了,您的编译器没有警告您尝试打开字符串指针而不是字符串数组的第一个字符 我的说:

“错误 C2050:开关表达式不是整数”

你仍然可以做一些事情:

switch(str[0])

(如果您在终止 null 上添加额外的检查,它是一个 1 字符的字符串)

老实说,我不认识您的 scanf() 语法,但无论如何我从不使用 scanf() ,因为如果您不小心,它可能会意外地超出您的缓冲区。 相反,我会使用 getchar() 一次读取一个字符,但有最大限制。

最后,您的 switch break 只会跳出内部 switch 语句。 您需要第二次休息才能跳出封闭循环。

确保我没有犯错或进一步修改:

#include <stdio.h>
#include <ctype.h>


char* input( char *s, size_t max ){
    size_t i = 0;
    int c;
    int skipped_space = 0;

    for(;;) {
        c = getchar();
        if(EOF == c) {
            // error
            break;
        }

        if(!skipped_space) {
            if(!isspace(c)) {
                skipped_space = 1;
                if(i < max) {
                    s[i++] = c;
                }
            }
        } else {
            if(isspace(c)) {
                break;
            }

            if(i < max) {
                s[i++] = c;
            }
        }
    }

    if(EOF != c  &&  i < max) {
        // success
        s[i] = '\0';
    } else {
        // failure or buffer overrun
        s = NULL;
    }

    return s;
}

void main()
{
    int done = 0;

    printf("Welcome to a string input/output example written in C! \n");
    printf("Type e to exit \n");
    printf(" \n");
    for(;;) {
        printf("> ");
        char str[100];
        if(input( str, 100 )) {
            switch(str[0]){
                case 'e'    :
                    if('\0' == str[1]) {
                        done = 1;
                        break;
                    }

                default:
                    printf("Your string is: \"%s\" \n", str);
                    break;
            }

            if(done)
                break;
        } else {
            printf("Error.\n", str);
        }
    }
}

如果您使用帮助器 function,则可以在 C 中使用带有字符串的开关。 在某些情况下,这可能是处理字符串输入的更优雅的方法。

这个助手 function 采用 null 终止模式的字符串,其中最后一个模式是双 null 终止(显式使用 \0 并隐含因为字符串的结尾)

int strswitch (const char * str, const char * patterns)
{
    int index = 0;
    size_t len;
    while (patterns && (len = strlen(patterns)) != 0) {
        if (strcmp(str, patterns) == 0)
            return index;
        index++;
        patterns += len + 1;    // next pattern
    }
    return -1;
}

然后要在助手中使用 switch 语句,请执行以下操作:

switch (strswitch(str,
    "e\0"
    "abc\0"
    "def\0"
    ))
{
    case 0 :    // "e"
        // handle "e" case
        break;
    case 1 : // "abc"
        // do something
        break;
    case 2 : // "def"
        // do something
        break;
    default :
        printf("Your string is: %s \n", str);
        break;
}

助手 function 不需要被限制为完全匹配。 根据您的需要,您可以编写一个只进行部分匹配或使用正则表达式等的程序。

暂无
暂无

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

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