首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > C# >

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

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

请问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"]);        }    }} 

热点排行