1

I'm starting out with coding and trying to make a very basic calculator. I want to run it in a cmd by calling it up with two numbers. So, in the correct directory, I would type "BasicCal 2 + 5" to run it.

This is the code in C#

using System;

public class BasicCal
{
    public static void Main(string [] args)
    {   
        Console.Write(args[0] + args[1] + args[2]);
        Console.ReadKey();
    }
}

Cmd then just prints "2+5" so I guess C# doesn't see an operator as an argument.

So I just need to know how to make C# recognize an operator when it's given as a parameter. Thanks in advance.

ChaiW
  • 11
  • 1
  • 1
    You need to analyze the string and branch (`if`) accordingly. You might also need to parse the other arguments into the correct type. – Markus Deibel Feb 07 '19 at 09:38
  • 1
    It's not that C# doesn't see an operator. You are passing *strings* with no special meaning and concatenating them. The computer can't guess that you want the middle string to act in a special way – Panagiotis Kanavos Feb 07 '19 at 09:39
  • In this answer https://stackoverflow.com/questions/53844/how-can-i-evaluate-a-c-sharp-expression-dynamically there are some good suggestions for how execute expressions on the fly – steve16351 Feb 07 '19 at 09:41
  • "C# doesn't see an operator as an argument" It´s more that C# can´t indicate if you ment an operator for numbers or just a plus-character within a string. – MakePeaceGreatAgain Feb 07 '19 at 09:42
  • @Markus Deibel I managed it by using `if (args[1] == "+")` and so on, it worked. Thanks! – ChaiW Feb 08 '19 at 06:24

1 Answers1

2

There are couple of problems here.

A) There is no sort of built-in way that allows C# compiler to understand what you're doing here so you'd have to implement the logics of parsing string argument with the sign:

switch(args[1])
{
   case "+": 
   {
      ... 
      break;
   }
   case "-": 
   {
      ... 
      break;
   }
   ... etc
}

B) Args are just strings so if we just do something like args[0] + args[1] the C# compiler doesn't know that its working with numbers and runs an overloaded + operator for string which does string concatenation.

Fabjan
  • 13,506
  • 4
  • 25
  • 52