-2

I want to do addition for two inputs in Console Application for C#.I don't want the user input for addition to be like

2

8

Output : 10

I want it to be like

2 8 

Output : 10

How can I accept a space character between the two inputs and add them up?Should I use one int variable or two int variables for two inputs?Thank you.

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69

2 Answers2

5

You need to string.Split() the input like so:

var inp = Console.ReadLine();
var split = inp.Split(' ');

if (split.Length == 2 
    && int.TryParse(split[0], out var a)  // assumes C#7 feature of inline var declaration 
    && int.TryParse(split[1], out var b)  // for out parameters, else declare ints earlyer
)
{
    // do something with a and b which are ints....
}
else
{
    // either not enough or too many or non-int input by the usere. handle it.
}

Just for giggles sake: if you want to be really lenient with inputs and like one-liners (I dont, dont do such things in production code ;o) you could do this :

// needs: using System.Linq; in addition to using System;

var any = false;
var sum = 0l;

Console.WriteLine(                                    // write something
    Console.ReadLine()                                   // what you read via console input
       .Split(' ')                                       // thats being split by' '
       .Where(part => int.TryParse(part, out var _))     // only use things parsable as int
       .Aggregate("", (acc, part) =>   // for each thing you got, create a string starting
       {                               // with an empty string
           any = true;                 // remeber we had some valid input
           if (acc.Length > 0)         // already something in string? 
               acc += " + ";                // add " + " to it
           acc += part;                // add the string that is parsable to int to result

           sum += int.Parse(part);     // it is parseable, so parse and add up
           return acc;                 // return what we have agg'ed so far to next cycle
       }) + (any ? $" = {sum}" : "No valid numbers in input."));
       // check if we got any, if so add sum to the console output, else the agg is ""
       // and we output our "error" message

Which will use every "correct" integer number in the input and print out the complete addition of correct integers if they fit into a long. It will ignore any number that is not parsable as integer, so in.MaxValue + 1 wont be added (too big), decimals wont be added. If no valid input is detected you get a message for that:

Input: hdfh 5 2h 6 7 -3 -9 222222222222222222222222222222222 76.43 2 3 4 -1000

Output: 5 + 6 + 7 + -3 + -9 + 2 + 3 + 4 + -1000 = -985

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
1

You have to take it in one move. and after you have to split it and calculate after that.

        startPoint:
        int output = 0;
        Console.Write("Input : ");
        string input = Console.ReadLine();
        string[] inputArray = input.Split(' ');
        foreach (string eachInputValue in inputArray)
        {
            try
            {
                output += Convert.ToInt32(eachInputValue);
            }
            catch (Exception ex)
            {
                Console.WriteLine("\nPlease input numeric type\n");
                goto startPoint;
            }
        }
        Console.Write("Output : " + output);
        Console.ReadKey();
    }

Thanks to @PatrickArtner and @IvanStefanov for warn me about my code's blind spots.

Kadir Kalkan
  • 248
  • 2
  • 10
  • 1
    @PatrickArtner you are right... :D ;) we'll got applecow... ;) – Ivan Stefanov Jan 06 '18 at 12:40
  • 1
    first, check/try your code and try to think about possibilities, and no one here say 'I know more than you"... your code can trow an exception... you provide answer 5 minutes after Patrick, so you can see something about `TryParse`... anyway, no one discouraging you, but no one "attacking" you too. Patrick was seriously about his comment, I just put little humor, not insulting you. – Ivan Stefanov Jan 06 '18 at 12:53
  • i am so sorry but i didn't know what means cow apple or applecow. i thougth it as "give a chance for think to who asked". And i said these. I couldn't find out the applecow's mean = "think about your code's exception possiblilities.My english is trash So i am really sorry :( – Kadir Kalkan Jan 06 '18 at 13:14
  • nevermind :) if you want to try to get into some linq: I added an linq example to my answer that's a bit advanced - dokumented by comments. See if you can get your head around it :) linq isreally helpfull sometimes. – Patrick Artner Jan 06 '18 at 13:17
  • wow a goto - havent seen that in a while :) +1 – Patrick Artner Jan 06 '18 at 13:22
  • yes i know, thank you :) but i think about the questioner is a newbie so he/she can understand easily with this way :) – Kadir Kalkan Jan 06 '18 at 13:22
  • hahaha :) i am trying to try every useful things :D – Kadir Kalkan Jan 06 '18 at 13:23