Search code examples
c#c++consoleiostream

C++ to C#: cin to Console.Read


Is there a way to read multiple inputs on the same line in C# like I would in C++?

I have included an example:

#include <iostream>
#include <string>
using namespace std;

int main ()
{
  cout << "Format: name age"<< endl;
  int age;
  string name;
  cin >> name >> age;
  return 0;
}

Solution

  • String.Split is the obvious solution here:

    string input = Console.ReadLine();
    string [] split = input.Split(` `);
    

    Then use the resultant array.

    You lose your "nice" variable names and have to convert from string to int - but you'd have to do that anyway.

    You can specify a set of split characters:

    string [] split = words.Split(new Char [] {' ', ',', '.', ':', '\t' });