Switch Statements Using String Input

2019-09-26 10:06发布

char type;
printf("What type of sort would you like to perform?\n");
scanf("%s", &type);
switch(type)
{
case 'bubble':
    bubble_sort();
case 'selection':
case 'insertion':
default:
    printf("invalid input\n");
}

I am trying to create a program which sorts a list with either bubble, selection, or insertion sort based on the user's input.

I have to use switch case to do so.

I have defined a variable "type" before the switch statement, and then use the scanf function to assign it either "bubble", "selection", or "insertion".

However, when I run the code and type in "bubble", it does not carry out my bubble_sort function (not shown here) and instead resorts to the default case.

How can I fix this issue?

I am slightly uncertain as to whether 'char' was the correct way to define my "type" variable, or whether switch statements can only be used with single characters.

Also, I apologise if my code is not formatted correctly, as I am new to this site.

Let me know if I need to add any more information to this question!

3条回答
ゆ 、 Hurt°
2楼-- · 2019-09-26 10:34

Strings in C are a pointer type, so when you try to put a string value into a switch statement or if statement like that you are really just comparing two pointers and not the values that they are point to.

You need a function like strcmp or strncmp to compare what is actually being pointed to

So, it should look like something like this;

char type[200];
printf("What type of sort would you like to perform?\n");
scanf("%199s", type);
if (strcmp(type,"bubble")==0) {
    bubble_sort();
} else
if (strcmp(type,"selection")==0) {
    something_selection();
} else
if (strcmp(type,"insertion")==0) {
    something_insetion();
} else {
    printf("invalid input\n");
}
查看更多
够拽才男人
3楼-- · 2019-09-26 10:35

This is not possible in C. Because, to compare two strings, strcmp() function should be used. But there is no way to add function in switch case.

查看更多
干净又极端
4楼-- · 2019-09-26 10:36

Since type is a char and the switch can use single characters, you could scan for one character using %c instead of %s

char type;
printf ( "What type of sort would you like to perform?\n");
printf ( "Enter b for bubble\n");
printf ( "Enter s for selection\n");
printf ( "Enter i for insertion\n");
scanf ( " %c", &type);
switch ( type)
{
    case 'b':
        bubble_sort();
        break;
    case 's':
        selection_sort();
        break;
    case 'i':
        insertion_sort();
        break;
    default:
        printf("invalid input\n");
}
查看更多
登录 后发表回答