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>
#开发者_StackOverflow社区include <string>
using namespace std;
int main ()
{
cout << "Format: name age"<< endl;
int age;
string name;
cin >> name >> age;
return 0;
}
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' });
Nope. You have to implement this yourself using Console.Read or Console.ReadLine.
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++.
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++]);
精彩评论