【问题标题】:Switch Statements Using String Input使用字符串输入的切换语句
【发布时间】:2017-05-19 02:25:14
【问题描述】:
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");
}

我正在尝试创建一个程序,该程序根据用户的输入使用冒泡、选择或插入排序对列表进行排序。

我必须使用 switch case 来做到这一点。

我在 switch 语句之前定义了一个变量“type”,然后使用 scanf 函数为其分配“bubble”、“selection”或“insertion”。

但是,当我运行代码并输入“bubble”时,它不会执行我的bubble_sort 函数(此处未显示),而是使用默认情况。

我该如何解决这个问题?

我有点不确定“char”是否是定义“类型”变量的正确方法,或者 switch 语句是否只能用于单个字符。

另外,如果我的代码格式不正确,我深表歉意,因为我是这个网站的新手。

如果我需要为这个问题添加更多信息,请告诉我!

【问题讨论】:

  • 首先,在bubble_sort(); 之后需要一个break,否则它会落入下一个案例。其次,这真的可以编译吗?在 C 中,字符串应该用双引号引起来。而且你不能在switch 中使用字符串。
  • 我刚刚添加了一个break,但同样的问题仍然存在。它确实编译
  • 认真对待编译器的警告。修复代码直到不再发出警告... sigh
  • 另外,刚刚注意到您将type 声明为char,但在scanf 中将其视为字符串。
  • 提示:在 C 中,单引号与双引号非常、非常、非常不同。

标签: c sorting switch-statement scanf


【解决方案1】:

C 中的字符串是指针类型,因此当您尝试将字符串值放入 switch 语句或类似的 if 语句中时,您实际上只是在比较两个指针,而不是它们所指向的值。

您需要像 strcmpstrncmp 这样的函数来比较实际指向的内容

所以,它应该看起来像这样;

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");
}

【讨论】:

  • 除了printf() 调用的参数之外,我在 OP 的代码中没有看到任何字符串。
  • 我应该在哪里添加这些功能?
  • @alk -- 这是新的一年,让我们宽容并帮助人们 -- 你说得对,他使用了单引号,但这显然不是他的意图
  • 好的,让它变得非常好,然后做"%199s" ... ;-)
  • “C 中的字符串是指针类型”——这是完全错误的! 1) C 没有字符串类型。 2) C“字符串”按照约定是char 数组,它们是不是指针!
【解决方案2】:

由于类型是 char 并且开关可以使用单个字符,因此您可以使用 %c 而不是 %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");
}

【讨论】:

    【解决方案3】:

    这在 C 中是不可能的。因为要比较两个字符串,应该使用 strcmp() 函数。但是没有办法在switch case中添加功能。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-05-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多