0

I have to make a calculator which will based on user's input, do specific operation. First of the input must be some kind of operator(+, -, *, etc.) and after the code checks which one of those is user's choice. I declared those operators as char, but my code editor says that I can't put char variables as case statements...What should I do? Code:

#include <stdio.h>
#include <math.h>

int main(){
char choice = "+", "*", "-", "/";
int a, b;
float outcome;

scanf("%c", &choice);

switch (choice)
{
    case "+":
        scanf("d% d%", &a, &b);
        outcome = a + b;
        printf("%.1f", outcome);
        break;
    case "*":
        scanf("%d %d", &a, &b);
        outcome = a * b;
        printf("%.1f", outcome); 
        break;
    case "-":
        scanf("%d %d", &a, &b);
        outcome = a - b;
        printf("%.1f", outcome);
        break;
    case "/":
        scanf("%d %d", &a, &b);
        outcome = a / b;
        printf("%.1f", outcome);
        break;

   }

return 0;
}
  • 3
    `"+"` is a *string*, not the single character literal `'+'`. Note the difference between double and single quotes. – Some programmer dude Apr 09 '20 at 11:28
  • 2
    `char choice = "+", "*", "-", "/";` <= does this even compile? – crashmstr Apr 09 '20 at 11:29
  • 1
    @crashmstr yes it does compile, but it certainly doesn't do what OP expects it to do. Short explanation: comma operator. Long explanation: The address of the last string literal is implicitly converted to an integer and truncated to a char's size. Should cause a shuckload of compiler warnings, but technically is legal. – datenwolf Apr 09 '20 at 11:34
  • Does this answer your question? [Why the switch statement cannot be applied on strings?](https://stackoverflow.com/questions/650162/why-the-switch-statement-cannot-be-applied-on-strings) – Mikel Rychliski Apr 11 '20 at 03:02

2 Answers2

1

You can use chars in switch but "+" and others are string literals not character literals, that would be '+'.

There are other problems in your code. For example it is not clear what you expect this to do (already fixed the quotes):

char choice = '+', '*', '-', '/';

A char is a single character.

Your code looks like C but not like C++. If you are actually using C++, you could use std::string and its find method, for example like this:

#include <string>
#include <iostream>

int main(){
    std::string choices = "+*-/";

    auto choice = choices.find('*');

    switch (choice){
        case 0: std::cout << "you chose +";break;
        case 1: std::cout << "you chose *";break;
        case 2: std::cout << "you chose -";break;
        case 3: std::cout << "you chose /";break;
        default: std::cout << "invalid operator";
    }
}
463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185
0

These are not chars, these are string literals.

Use '+' instead of "+".

Michael
  • 932
  • 6
  • 15