-1

I'm trying to build a calculator by just entering the operation in 1 line. I got stuck when i try to split the input and use a foreach loop

string input = "28 + 2";
        string[] array = input.Split();
        foreach(string value in array)
        {
            // trying to assign the first value of foreach to 'num1'
            int num1 = [0];
        }

what I need here is how to assign the first and third value to a variable so I can use it to build the calculator but, I think I use the wrong way to assign it

note: the split funtion is working. if i do this:

string input = "28 + 2";
string[] array = input.Split();
        foreach(string value in array)
        {
            Console.WriteLine(value);
        }

I get the output 28, +, 2 I will use this function to not just add two numbers but divide, multiply and subtract them. So the answer i need here is how to actually assign split values to a variable not split the string

Emre
  • 1
  • 3
  • 1
    You should try splitting the string using the spaces, something like `input.Split(' ');` – Aethers haven Nov 28 '20 at 13:14
  • @Aethershaven splitting the string is fine, i get the values printed out to console when i do 'Console.WriteLine(value)' but cant figure how to assign these values to a variable – Emre Nov 28 '20 at 13:18
  • Try this: https://stackoverflow.com/questions/21950093/string-calculator – Hasan Fathi Nov 28 '20 at 13:38

2 Answers2

0
string input = "28 + 2";
string[] array = input.Split('+');
foreach(string value in array)
{
    int num1 = int.Parse(value);
}
r_piramoon
  • 141
  • 1
  • 6
  • 4
    Please don't post only code as answer, but also provide an explanation what your code does and how it solves the problem of the question. Answers with an explanation are usually more helpful and of better quality, and are more likely to attract upvotes. – Boken Nov 28 '20 at 13:54
0

If you are only working with two numbers, you don't even need a loop, you could do something like this:

string input = "28 + 2";
string[] array = input.Split();
int num1 = int.Parse(array[0]);
int num2 = int.Parse(array[2]);
Aethers haven
  • 86
  • 2
  • 6