日期:2014-05-17  浏览次数:20880 次

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