C 解析用户输入,字符串比较

C 解析用户输入,字符串比较,c,string,parsing,C,String,Parsing,在我的函数中,我想检查传入的C样式字符串参数是否满足某些条件。如果用户输入“I/P”,编译器总是认为我想处理“I”。。。同样,如果用户输入“DNA”,编译器就不会认为“D”是输入的。。。我怎样才能解决这个问题 void parseUserInput(char *userInput) { if (strncmp(userInput, "D", 1) == 0) { printf("

在我的函数中,我想检查传入的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");
    }
void parseUserInput(char*userInput)
{
如果(strncmp(用户输入,“D”,1)==0)
{
printf(“>>此输入应指向>函数…\n”);
评估等级(用户输入);
}
else if(strncmp(userInput,“I”,1)==0)
{
printf(“学生有特殊情况:I(不完整)\n”);
}
else if(strncmp(用户输入,“I/P”,3)=0)
{
printf(“学生有特殊情况:I/P(正在处理)\n”);
}
else if(strncmp(用户输入,“DNA”,3)=0)
{
printf(“学生有特殊情况:DNA(未参加)\n”);
}

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

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");
    }
}
void parseUserInput(char*userInput)
{
如果(strncmp(用户输入,“DNA”,3)=0)
{
printf(“学生有特殊情况:DNA(未参加)\n”);
}
else if(strncmp(用户输入,“D”,1)=0)
{
printf(“>>此输入应指向>函数…\n”);
评估等级(用户输入);
}
else if(strncmp(用户输入,“I/P”,3)=0)
{
printf(“学生有特殊情况:I/P(正在处理)\n”);
}
else if(strncmp(userInput,“I”,1)==0)
{
printf(“学生有特殊情况:I(不完整)\n”);
}
}

更改检查顺序?应该先进行更具体的检查。@kaylum现在说重新排序,我还有其他检查,如“AU”、“A+”和“A”,在重新排序之后,我仍然遇到这个问题。如果你做得正确,你就不会有问题。如果你认为你仍然有问题,请提供确切的细节。把更长的比较放在前面。@kaylum我觉得很笨,非常感谢,我重新排序正确,现在它工作了!