user295190
user295190

Reputation:

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;
}

Upvotes: 5

Views: 24558

Answers (4)

bmi
bmi

Reputation: 811

Try someting like this:

    var allInputs = Console.In
        .ReadToEnd()
        .Split(new string[] { " ", Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);

    int argPtr = 0;

    var strPar1 = allInputs[argPtr++];
    var intPar2 = int.Parse(allInputs[argPtr++]);
    var strPar3 = allInputs[argPtr++];
    var intPar4 = int.Parse(allInputs[argPtr++]);

Upvotes: 0

Svetlin Nakov
Svetlin Nakov

Reputation: 1669

You could use this C# std::cin class written by Svetlin Nakov which behaves like std::cin in C++ and java.util.Scanner. It can read numbers, ints, doubles, decimals and string tokens from the console, just like cin >> a >> b in C++.

Upvotes: 0

ChrisF
ChrisF

Reputation: 137148

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' });

Upvotes: 5

Robert Jeppesen
Robert Jeppesen

Reputation: 7877

Nope. You have to implement this yourself using Console.Read or Console.ReadLine.

Upvotes: 2

Related Questions