-4

INPUT

67 89 (in single line)

I have to input two numbers from console , and store in two different integers variable . HOw to do it.

leppie
  • 115,091
  • 17
  • 196
  • 297
user3529205
  • 175
  • 3
  • 12
  • 3
    Read the first number, then read the second number. – Sergey Kalinichenko Dec 21 '14 at 12:05
  • Even if the core of the question is the same, it DOES NOT mean that the natural language expression is the same. > How to read Two numbers in c# > Reading two integers in one line using C# It is not recommended to give a negative rate. – 蔡宗容 Oct 05 '19 at 05:16

3 Answers3

5

This will read a line from the console, split the string, parse the integers, and output a list. You can then take each number from the list as needed.

Console.ReadLine().Split().Select(s => int.Parse(s)).ToList()

If there will always be two numbers you can do it as follows:

var integers = Console.ReadLine().Split().Select(s => int.Parse(s)).ToArray();
int first = integers[0];
int second = integers[1];

Areas for improvement:

  • You might want to use TryParse instead of Parse and output a friendly error message if the input does not parse

  • If you require exactly 2 numbers (no more, no less) you might want to check the length of integers and output a friendly error message if <> 2


TryParse() example as requested:

var numbers = new List<int>();

foreach (string s in Console.ReadLine().Split())
{
    if (int.TryParse(s, out int number))
        numbers.Add(number);
    else
        Console.WriteLine($"{s} is not an integer");
}
Stephen Kennedy
  • 20,585
  • 22
  • 95
  • 108
  • `Split()` [has no overload that accepts no arguments](http://msdn.microsoft.com/en-us/library/system.string.split(v=vs.110).aspx). **EDIT**: But this seems to work fine. Learned something new today :P – RobIII Dec 21 '14 at 12:09
  • @Robll it worked in LinqPad... MSDN: "If the separator parameter is null or contains no characters, white-space characters are assumed to be the delimiters." seperator is a params argument. – Stephen Kennedy Dec 21 '14 at 12:11
  • 1
    Yeah, never realized it could be used this simple :P – RobIII Dec 21 '14 at 12:12
  • How would I apply Int32.TryParse in method you described above? – Barrosy Oct 12 '19 at 09:57
  • 1
    @Barrosy I've added an example – Stephen Kennedy Oct 12 '19 at 19:07
3
using System;
public class Program
{
    static void Main(string[] args)
    {
        var numbers = Console.ReadLine();
        var numberList = numbers.Split(' ');
        var number1 = Convert.ToInt32(numberList[0]);
        var number2 = Convert.ToInt32(numberList[1]);
        Console.WriteLine(number1 + number2);
        Console.ReadKey();
    }
}

If you executing from other program the you need to read from the args

Mahesh Malpani
  • 1,782
  • 16
  • 27
2
var result = Console.ReadLine().Split(new [] { ' '});

Something along those lines, top of my head.

See the documentation for Console.ReadLine() and String.Split()

Using Linq you can then project into an int array:

var result = Console.ReadLine()
                    .Split(new[] { ' ' })  //Explicit separator char(s)
                    .Select(i => int.Parse(i))
                    .ToArray();

And even a bit terser:

var result = Console.ReadLine()
                    .Split()  //Assuming whitespace as separator
                    .Select(i => int.Parse(i))
                    .ToArray();

Result is now an array of ints.

RobIII
  • 8,488
  • 2
  • 43
  • 93
  • Further to our exchange of comments below my answer, note that even if Split() did not accept null or zero arguments you don't need to create an array of chars. Because of the params keyword the compiler will take care of this for you. So, you would only need to write `.Split(' ')` or say if there are 2 seperators `.Split(' ', '@')`. See http://msdn.microsoft.com/en-gb/library/w5zay9db.aspx – Stephen Kennedy Dec 21 '14 at 12:20