首页 > 解决方案 > 解析用户输入,字符串比较

问题描述

在我的函数中,我想检查传入的 C 样式字符串参数是否满足某些条件。如果用户输入“I/P”,编译器总是认为我想要处理“I”......如果用户输入“DNA”,编译器也会停止认为“D”被输入......我要解决这个问题吗?

     void parseUserInput(char *userInput)
    {
           if (strncmp(userInput, "D", 1) == 0)
        {
                printf(">> This input should be directed to the << assessGrade(char *) >> function ...\n");
                assessGrade(userInput);
        }
            else if (strncmp(userInput, "I", 1) == 0)
        {
                printf("Student has Special Situation : I (Incomplete)\n");
        }
            else if (strncmp(userInput, "I/P", 3) == 0)
        {
                printf("Student has Special Situation : I/P (In Process)\n");
        }
           else if (strncmp(userInput, "DNA", 3) == 0)
        {
               printf("Student has Special Situation : DNA (Did Not Attend)\n");
    }

标签: cstringparsing

解决方案


一种解决方案是更改检查的顺序,以便首先进行较长的前缀比较。例如:

void parseUserInput(char *userInput)
{
    if (strncmp(userInput, "DNA", 3) == 0)
    {
        printf("Student has Special Situation : DNA (Did Not Attend)\n");
    }
    else if (strncmp(userInput, "D", 1) == 0)
    {
        printf(">> This input should be directed to the << assessGrade(char *) >> function ...\n");
        assessGrade(userInput);
    }
    else if (strncmp(userInput, "I/P", 3) == 0)
    {
        printf("Student has Special Situation : I/P (In Process)\n");
    }
    else if (strncmp(userInput, "I", 1) == 0)
    {
        printf("Student has Special Situation : I (Incomplete)\n");
    }
}

推荐阅读