读书人

请教C#能否像C语言scanf(quot;%d %dquot;amp;a,

发布时间: 2012-09-27 11:11:17 作者: rapoo

请问C#能否像C语言,scanf("%d %d",&a,&b),用户就能一行用空格隔开2数字,然后一起读入?
请问C#能否像C语言,scanf("%d %d",&a,&b),用户就能一行用空格隔开2数字,然后一起读入?


这样用C语言的话,输入 1 2 就能使得 a=1 b=2

但C#中不知怎么实现。不想一行只能输入一个数字

[解决办法]
使用可变参数:

C# code
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Text.RegularExpressions;namespace ConsoleApplication1{    class Program    {        static Dictionary<string, string> MyScanf(string format, params string[] values)        {             var result = Regex.Match(Console.ReadLine(), format).Groups;            return values.Select((x, i) => new { key = x, value = result[i + 1].Value })                         .ToDictionary(x => x.key, x => x.value);        }        static void Main(string[] args)        {            var input = MyScanf(@"(\d+) (\d+)", "a", "b");            Console.WriteLine("your input is a = {0}, b = {1}.", input["a"], input["b"]);        }    }} 

读书人网 >C#

热点推荐