[英]Parsing User Input, string comparison
在我的 function 中,我想检查传入的 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)
{
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");
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.