-3

How to make calculator with input string in its operation selection?, i have tried but it doesn't work. My lecture assigned :)

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;
user0042
  • 7,917
  • 3
  • 24
  • 39
  • 3
    Your code is incomplete; in particular, it seems to be missing a main() function. Please edit your code so it's a [Minimal, Complete, and Verifiable](https://stackoverflow.com/help/mcve) example of your problem, then we can try to reproduce and solve it. You should also read [How to Ask](https://stackoverflow.com/help/how-to-ask). – H.S. Oct 30 '17 at 10:51
  • 1
    Why switch statement cannot be applied on strings? https://stackoverflow.com/questions/650162/why-switch-statement-cannot-be-applied-on-strings – Aditi Rawat Oct 30 '17 at 10:56
  • 2
    `'tambah'` This is definitely not a char. – DimChtz Oct 30 '17 at 10:57
  • `scanf("%s", (char *) &choose);` is mostly not correct. – Ajay Brahmakshatriya Oct 30 '17 at 11:25

1 Answers1

1

Using string (considering you use strings since in your example you just put several chars into literal, which is supposed to be a char) directly in switch() statement in C is a terrible idea. I suggest enuming the possible options and feed them in a strcmp in order to match your operation and branch accordingly.

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

Offtopic: Also please consider using english for all labels and variable names in your program when you're about to seek guidance in an international forum.

Gnqz
  • 3,292
  • 3
  • 25
  • 35