在同一行C#

时间:2016-11-10 11:58:22

标签: c# c

我有一个问题。我在一个控制台应用程序上工作,我想在同一行上读取3变量。

使用C语言我们可以写这个

int a;
string b;
int c;

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

当我启动程序时,我写道:1 + 1在同一行,a = 1 b =" +" c = 1

如何在C#中使用console.readline()创建相同的内容?

提前谢谢你,

Nico

2 个答案:

答案 0 :(得分:0)

此答案已从reading two integers in one line using C#修改。所以你可以按照这个答案中的描述做几种方式,但我建议如下:

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

我建议关注该链接,因为有更多方法可供描述。

答案 1 :(得分:0)

不,没有等价物,但你可以轻松创建一个:

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

但是你必须解析你的调用代码中的每个参数:

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

如果你想验证字符串和数字的格式,你可能还需要一个正则表达式:

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

现在再次需要解析:

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

请记住,正则表达式中的第一个组总是包含完整的匹配字符串,因此第一个捕获组的索引为1。

相关问题