简体   繁体   中英

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

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.

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++]);

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++.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM