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!
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
orstrncmp
to compare what is actually being pointed toSo, it should look like something like this;
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.
Since type is a char and the switch can use single characters, you could scan for one character using %c instead of %s