0

I have a question. I work on a console application and I would like Read 3 variable on the same line.

With the language C we can write this

int a;
string b;
int c;

scanf("%d %s %d", &a, &b, &c);

When I start the program I write : 1+1 on the same line and a = 1 b = "+" c = 1

How can I make the same in C# with console.readline() ?

Thank you in advance,

Nico

Adil
  • 146,340
  • 25
  • 209
  • 204
  • No such possiblity in c#. But you can find custom implementation, f.e: http://www.blackbeltcoder.com/Articles/strings/a-sscanf-replacement-for-net – pwas Nov 10 '16 at 12:01
  • 3
    [reading two integers in one line using C#](http://stackoverflow.com/questions/3881826/reading-two-integers-in-one-line-using-c-sharp) have look at this question, it should be what you are looking for – Cal-cium Nov 10 '16 at 12:02

2 Answers2

0

This answer is modified from reading two integers in one line using C#. So you can do it several ways as described in this answer, but i would suggest like:

//Read line, and split it by whitespace into an array of strings
string[] scanf= Console.ReadLine().Split();

//Parse element 0
int a = int.Parse(scanf[0]);

//Parse element 1
string b = scanf[1];

//Parse element 2
int c = int.Parse(scanf[2]);

I would suggest following the link as there is more ways described.

Community
  • 1
  • 1
Cal-cium
  • 654
  • 12
  • 22
0

No, there is no equivalent, but you can easily create one:

void Scanf(out string[] values)
{
    values = Console.ReadLine().Split();
}

However you have to parse every argument in your calling code:

int a;
string b;
int c;
string[] r;

scanf(out r);
int.TryParse(r[0], out a);
b = r[1];
int.TryParse(r[2], out c);

If you want to verify the format of the strings and numbers also you probably need a regex:

var r = new Regex("(\\d+) (\\S+) (\\d+)");
var values = r.Matches(Console.ReadLine())[0];

Now again you need to parse:

int.TryParse(values.Groups[1], out a);
b = values.Groups[2];
int.TryParse(values.Groups[3], out c);

Remember that the first group within a regex allways contains the complete match-string, so the first capturing group has index one.

MakePeaceGreatAgain
  • 35,491
  • 6
  • 60
  • 111