views:

60

answers:

2

I am trying to learn C# coming from C++. I am writing just some basic console stuff to get a feel for it and was wondering if it is possible to do simple chaining of inputs in C#. For example in C++:

cout<<"Enter two numbers: ";
cin >> int1 >> int2;

You could then just input 3 5 and hit enter and the values will be fine. In C# however I have to split it up(as far as I can tell) like this:

Console.Write("Enter the first number: ";
int1 = (char)Console.Read();
Console.Writeline("");
Console.Write("Enter the second number: ";
int2 = (char)Console.Read();

Maybe I am just missing something.

+2  A: 

you can read the entire line with Console.ReadLine and can get the two variables in a variety of ways split, basic test parsing, or Regex.


A short Ex

  Console.WriteLine("Enter two Numbers");
  int Num1 = 0 ,Num2 = 0 ;
  Match M = Regex.Match(Console.ReadLine(),@"(\d+) (\d+)");
  Num1 = int.Parse(M.Groups[1].Value);
  Num2 = int.Parse(M.Groups[2].Value);

  //Using Split 
  Console.WriteLine("Enter two Numbers");
  string[] Ints = (Console.ReadLine().Split(' '));
  Num1 = int.Parse(Ints[0]);
  Num2 = int.Parse(Ints[1]);
rerun
A: 

There's nothing that prevents input chaining from working in C#, you just won't get the nice operator syntax because C# lets you redefine fewer operators.

Writing an extension method to let you do:

Console.In.Read(out int1).Read(out int2);

is left as an exercise for the reader.

Ben Voigt