如何在C中切换字符串?

时间:2014-11-29 12:55:35

标签: c string

如何在switch语句中使用字符串?现在我在switch语句中使用了字符串的第一个字母。这是我的代码。我想使用char a,b,c中的整个字符串作为switch中的输入。怎么样?

int main()
{
    char input[10];
    int x, y, i;
    int AX;
    char a[] = "ADD";
    char b[] = "PRT AX";
    char c[] = "EXIT";

    for (i = 0; i < 100; i++)
    {
        printf("\nType ADD following the two numbers to be added\n");
        printf("     PRT AX to display the sum\n");
        printf("     EXIT to exit program\n");
        printf("---->");
        scanf("%s", &input);

        switch (input[0])
        {

        case 'A':

            printf("\nEnter two numbers you want to add:\n");
            scanf("%d %d", &x, &y);
            break;
        case 'P':
            printf("Sum: %d\n\n", x + y );
            break;
        case 'E':
            exit(0);
        default:
            i++;
        }
    }

    return 0;
}

2 个答案:

答案 0 :(得分:1)

你做不到。 C11标准非常清楚switch语句中允许的内容:

  

6.8.4.2 switch语句

     

<强>约束

     

1 开关语句的控制表达式应具有   整数类型。

     

[...]

     

3每个 case 标签的表达式应为整数常量   表达式中没有两个 case 常量表达式   转换后,开关语句应具有相同的值。 ...

注意:字符在C中具有整数类型。

相反,您希望使用strcmp来比较字符串。 不要使用比较运算符!如果两个字符串相等,strcmp将返回0

答案 1 :(得分:1)

尝试类似

的内容
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main(void) 
{
    char input[10];
    int x, y, i;

    const char * a[3] = 
    {
        "ADD",
        "PRT AX",
        "EXIT",
    };

    enum CHOICE { ADD, PRT_AX, EXIT, WRONG } choice;

    for ( i = 0; i < 100; i++ )
    {
        size_t n;
        printf( "\nType ADD following the two numbers to be added\n" );
        printf( "     PRT AX to display the sum\n" );
        printf( "     EXIT to exit program\n" );
        printf( "---->" );
        fgets( input, sizeof( input ), stdin );

        n = strlen( input );
        if ( n && input[n-1] == '\n' ) input[n-1] = '\0';

        choice = ADD;
        while ( choice != WRONG && strcmp( a[choice], input ) != 0 )
        {   
            choice = ( enum CHOICE )( choice + 1 );        
        }

        switch ( choice )
        {
        case ADD:
            printf( "\nEnter two numbers you want to add:\n" );
            scanf( "%d %d", &x, &y );
            fgets( input, sizeof( input ), stdin );
            break;
        case PRT_AX:
            printf( "Sum: %d\n\n", x + y );
            break;
        case EXIT:
            puts( "Exiting..." );
            exit(0);
        default:
            i++;
        }
    }
    return 0;
}

另请注意,您应该使用fgets阅读wntire line,然后应用sscanf