【问题标题】:calculator with input string in its operation selection [closed]在其操作选择中带有输入字符串的计算器[关闭]
【发布时间】:2017-10-30 10:48:39
【问题描述】:

如何在其操作选择中使用输入字符串制作计算器?我试过了,但它不起作用。我的讲座分配:)

printf("choose:");
scanf("%s", (char *) &choose);

switch(choose)
{
case 'tambah':
printf("Masukkan Nilai 1:");
scanf("%d", &x);
printf("Masukkan Nilai 2:");
scanf("%d", &y);
hasil = tambah(x,y);
printf("%d + %d = %d", x, y, hasil);
break;

case 'kurang':
printf("Masukkan Nilai 1:");
scanf("%d", &x);
printf("Masukkan Nilai 2:");
scanf("%d", &y);
hasil = kurang(x,y);
printf("%d - %d = %d", x, y, hasil);
break;

【问题讨论】:

  • 您的代码不完整;特别是,它似乎缺少一个 main() 函数。请编辑您的代码,使其成为您问题的Minimal, Complete, and Verifiable 示例,然后我们可以尝试重现并解决它。您还应该阅读How to Ask。
  • 为什么switch语句不能应用于字符串? stackoverflow.com/questions/650162/…
  • 'tambah' 这绝对不是字符。
  • scanf("%s", (char *) &choose); 大多不正确。

标签: c string calculator


【解决方案1】:

直接在 C 中的 switch() 语句中使用字符串(考虑到您使用字符串,因为在您的示例中您只是将几个字符放入文字中,这应该是 char)是一个糟糕的主意。我建议枚举可能的选项并将它们提供给strcmp,以便相应地匹配您的操作和分支。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

enum {
tambah = 0,
kurang = 1
};

int decodeLineType(const char* strAction)
{
  int i = 0;

  char acAllowedCodes[2][7] = {"tambah","kurang"};

  for(; i < 2; ++i)
  {
    if (strncmp(strAction, acAllowedCodes[i], strlen(acAllowedCodes[i])) == 0)
    {
      return i;
    }
  }

  return(-1);
}

int main()
{
    char choose[30] = {0};
    scanf("%s", choose);
    switch(decodeLineType(choose))
    {
       case tambah :
         /* some logic here*/
       break;
       case kurang :
         /* some logic here*/
       break;
       default:
       break;
    }
    return(0);
}

题外话:当您准备在国际论坛寻求指导时,请考虑在您的程序中为所有标签和变量名称使用英文。

【讨论】:

    猜你喜欢
    • 2014-03-23
    • 1970-01-01
    • 1970-01-01
    • 2021-02-26
    • 1970-01-01
    • 1970-01-01
    • 2012-09-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多