问题描述
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.
我必须使用开关盒.
我在switch语句之前定义了一个变量"type",然后使用scanf函数将其分配为"bubble","selection"或"insertion".
I have defined a variable "type" before the switch statement, and then use the scanf function to assign it either "bubble", "selection", or "insertion".
但是,当我运行代码并键入"bubble"时,它不执行我的bubble_sort函数(此处未显示),而是采用默认情况.
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.
如何解决此问题?
对于'char'是定义我的"type"变量的正确方法还是switch语句是否只能用于单个字符,我有点不确定.
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!
推荐答案
由于类型是字符,并且开关可以使用单个字符,因此可以使用%c而不是%s扫描一个字符
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");
}
这篇关于使用字符串输入切换语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!