reading two integers in one line using C#

前端 未结 12 1593
旧巷少年郎
旧巷少年郎 2020-11-30 09:37

i know how to make a console read two integers but each integer by it self like this

int a = int.Parse(Console.ReadLine());
int b = int.Parse(Console.ReadLin         


        
相关标签:
12条回答
  • 2020-11-30 10:01
    int a, b;
    string line = Console.ReadLine();
    string[] numbers= line.Split(' ');
    a = int.Parse(numbers[0]);
    b = int.Parse(numbers[1]);
    
    0 讨论(0)
  • 2020-11-30 10:05

    You need something like (no error-checking code)

    var ints = Console
                .ReadLine()
                .Split()
                .Select(int.Parse);
    

    This reads a line, splits on whitespace and parses the split strings as integers. Of course in reality you would want to check if the entered strings are in fact valid integers (int.TryParse).

    0 讨论(0)
  • 2020-11-30 10:07

    Read the line into a string, split the string, and then parse the elements. A simple version (which needs to have error checking added to it) would be:

    string s = Console.ReadLine();
    string[] values = s.Split(' ');
    int a = int.Parse(values[0]);
    int b = int.Parse(values[1]);
    
    0 讨论(0)
  • 2020-11-30 10:07

    in 1 line, thanks to LinQ and regular expression (no type-checking neeeded)

    var numbers = from Match number in new Regex(@"\d+").Matches(Console.ReadLine())
                        select int.Parse(number.Value);
    
    0 讨论(0)
  • 2020-11-30 10:09

    Then you should first store it in a string and then split it using the space as token.

    0 讨论(0)
  • 2020-11-30 10:12
    public static class ConsoleInput
    {
        public static IEnumerable<int> ReadInts()
        {
            return SplitInput(Console.ReadLine()).Select(int.Parse);
        }
    
        private static IEnumerable<string> SplitInput(string input)
        {
            return Regex.Split(input, @"\s+")
                        .Where(x => !string.IsNullOrWhiteSpace(x));
        }
    }
    
    0 讨论(0)
提交回复
热议问题