c - 解析用户输入,字符串比较
问题描述
在我的函数中,我想检查传入的 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");
}
}
推荐阅读
- java - 为 ZipOutputStream 跳过 ZipEntry 中的字节
- python - 使用 Python 移动文件
- css - 创建边框底部小于元素,中间更厚
- excel - 在 Excel 中使用嵌套公式
- r - 为什么在 for 循环中添加 return() 会有所不同?
- android - Android 和 Room:插入有效,查询无效
- widget - 如何在 Wordpress 中按“年”然后按“月”显示“档案”小部件布局(侧边栏)?
- javascript - 反应路由器 | 仅在页面刷新时加载组件
- python - 当有多个选择时,在 numpy 数组中查找随机事件
- visual-studio-code - VS-Code 集成终端中的 ZSH agnoster 主题不显示符号