c - C语言中如何切换字符串?

标签 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;
}

最佳答案

尝试类似的事情

#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 读取整行,然后应用 sscanf

关于c - C语言中如何切换字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27202510/

相关文章:

c - 字符串开头出现奇怪的字符

c - VirtualBox 如何处理 guest Linux 的中断?

python - 使用 python 将包含参数的字符串转换为数组

c - scanf 和 printf 不打印正确的值

c - 使用 strstr 确定给定字符串是否包含带空格的字符串 [C]

c - 破坏红色区域的内联汇编

c++ - Visual C++ 10(又名 2010)与 Visual C++ 9(又名 2008)相比

arrays - COBOL 解串到数组中

c - 如何在C中将字符串初始化为链表结构

c++ - 在x86_64模式下,寄存器中无法容纳64位数字