c - 如何接受用户的全部和部分输入字符串?
问题描述
我正在开发一个接受来自用户的字符串的 C 程序。
添加、显示、打印、查找、删除和退出。
该程序必须允许用户键入部分或完整的选项名称(如上所列)来选择一个选项。
例如,如果用户给出“a”或“ad”,程序必须接受它作为添加选项。(这部分我有问题)
我的代码如下:
while(strcmp(input, "quit") != 0)
{
printf("Add a record");
printf("\nShow a record");
printf("\nDelete a record");
printf("\nFind a record");
printf("\nPrint all records");
printf("\nQuit");
scanf("%s", &choice);
/*Above it says it should accept a or ad for 'add'. In my actual code it only accepts add. That's what I need help with. */
if(strcmp(choice, "add") == 0)
{
addMenu(&start);
}
else if(strcmp(choice, "delete") == 0)
{
deleteMenu(&start);
}
else{
printf("\nInvalid menu choice!");
}... other options
}
解决方案
最简单的方法可能是结合strlen
和strncmp
:
size_t len = strlen(choice);
if(strncmp(choice, "add", len) == 0)
{
addMenu(&start);
}
// likewise for the rest
如果只有"a"
,它只会比较第一个字符。
用"add"
它将比较三个字符。它将尝试比较四个,这将达到文字的空终止符
,并失败。"adda"
"add"
您可能希望确保这一点len != 0
,否则它将匹配每个命令。
推荐阅读
- symfony - 如何使用 Symfony 序列化器将字符串转换为 int
- c# - 从代码将调试器附加到正在运行的进程
- python - 如何将 Scraper API 与 Scrapy SitemapSpider 集成
- python - 协程对象不是 JSON 可序列化的
- c# - 如何获取动态制作的单击按钮的索引
- javascript - 如何为谷歌桑基图设置特定节点位置?
- spring - 控制器方法中 requestBody 上的 Spring Boot @Valid 不起作用
- python - not 关键字的位置在这里会有所不同吗?
- python - face_recognition python flask不处理传递的图像
- python - VSCode 笔记本中未显示 Python 警告