使用带有switch()的字符串命令使用#define

时间:2017-04-19 23:47:42

标签: c switch-statement

我试图通过使用关键字而不是整数来使用switch()语句。我已经将我的问题写成一个更简单直接的例子,以便更好地指出我的目标。我的相关代码:

#include <stdio.h>
#include <stdlib.h>

#define put 0
#define get 1
#define run 2

int main () {
    int ch;

    printf("%s", "Please enter a command: ");
    scanf("%d", ch);

    switch (ch) {
        case 0:
            puts("You chose \"put\" as a command.");
            break;
        case 1:
            puts("You chose \"get\" as a command.");
            break;
        case 2:
            puts("You chose \"run\" as a command.");
            break;
    }
}

理想情况下,当我扫描用户输入时,我希望用户能够使用上述#define语句中提供的命令。因此,系统会提示用户输入值put,程序将输出case 0。这可能是switch()吗?

2 个答案:

答案 0 :(得分:1)

您需要一个将用户输入转换为命令的功能。 e.g。

int stringToCommand(char* cmd)
{
   if (strcmp(cmd, "put") == 0)
       return put;
   ...
}

然后你可以在开关中使用#defines

int cmd = stringToCommand(userInput);
switch (cmd) {
    case put:
        puts("You chose \"put\" as a command.");
        break;
    ...

通常对于这种情况,我会查看枚举而不是依赖#defines。

答案 1 :(得分:0)

这里显示了如何实现switch语句。

#include <stdio.h>
#include <string.h>

int main(void) 
{
    const char * key_word[] = { "put", "get", "run" };
    const size_t N = sizeof( key_word ) / sizeof( *key_word );

    enum { PUT, GET, RUN };

    char command[5];

    printf( "Please enter a command: " );
    fgets( command, sizeof( command ), stdin );

    command[ strcspn( command, "\n" ) ] = '\0';

    size_t i = 0;

    while ( i < N && strcmp( command, key_word[i] ) != 0 ) i++;

/*  
    if ( i != N )
    {
        printf( "You chose \"%s\" as a command.\n", key_word[i] );
    }
    else
    {
        puts( "Invalid input." );
    }
*/

    switch ( i )
    {
    case PUT:
        printf( "You chose \"%s\" as a command.\n", key_word[i] );
        break;
    case GET:
        printf( "You chose \"%s\" as a command.\n", key_word[i] );
        break;
    case RUN:
        printf( "You chose \"%s\" as a command.\n", key_word[i] );
        break;
    default:
        puts( "Invalid input." );
        break;
    }

    return 0;
}

程序输出可能看起来像

Please enter a command: get
You chose "get" as a command.