首页 > 解决方案 > 如何接受用户的全部和部分输入字符串?

问题描述

我正在开发一个接受来自用户的字符串的 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
}

标签: c

解决方案


最简单的方法可能是结合strlenstrncmp

size_t len = strlen(choice);
if(strncmp(choice, "add", len) == 0)
{
    addMenu(&start);
}
// likewise for the rest

如果只有"a",它只会比较第一个字符。
"add"它将比较三个字符。它将尝试比较四个,这将达到文字的空终止符
,并失败。"adda""add"

您可能希望确保这一点len != 0,否则它将匹配每个命令。


推荐阅读