1

I want to enter a number from console but i want't beside each other . For example:-

 int x = int.Parse(Console.ReadLine()); 
 int y = int.Parse(Console.ReadLine());

Example for input:-

3

4

And , want't to display like that:-

3 4

2 Answers2

2

Use string.Split:

string input = Console.ReadLine();
var parts = input.Split(' ');
x = int.Parse(parts[0]);
y = int.Parse(parts[1]);

Notice that I didn't take care of cases where the input doesn't have the space not if it can't be parsed into a number.

  • For the spaces - if it is for sure one a single space you want then you can check that the length is of 2. If you want any amount of numbers then use linq's Select on the .Split
  • For the parsing - check TryParse
Gilad Green
  • 36,708
  • 7
  • 61
  • 95
1

Console.ReadLine() reads input until a user hits the enter key, which will advance the cursor to the next line.

You want Console.Read() or perhaps Console.ReadKey(). Just keep in mind that you'll have to implement logic to determine when input is ended - for example, checking whether the input was the space key, or some other non-numeric key. ReadLine is handling that for you automatically right now, whereas Read/ReadKey will not.

See also: Difference between Console.Read() and Console.ReadLine()?

Community
  • 1
  • 1
Dan Field
  • 20,885
  • 5
  • 55
  • 71