Fred
Fred

Reputation: 240

How to accept a full and partial input String from the user?

I am working on a C program which accepts a string from the user.

add, show, printall, find, delete, and quit.

The program must allow the user to type a partial or full option name (listed above) to choose an option.

For example, if the user gives 'a' or 'ad', the program must accept it as an option for add. (I AM HAVING TROUBLE WITH THIS PART)

My code below:

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
}

Upvotes: 2

Views: 299

Answers (1)

Siguza
Siguza

Reputation: 23890

The easiest way to do this is probably to combine strlen and strncmp:

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

If there is only "a", it will only compare the first char.
With "add" it will compare three characters.
With "adda" it will try to compare four, which will hit the null terminator of the "add" literal, and fail.

You might want to make sure that len != 0 though, otherwise it would match every command.

Upvotes: 4

Related Questions