使用C#在一行中读取两个整数

我知道如何使控制台读取两个整数,但每个整数由它自己像这样

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

如果我输入两个数字,即(1 2),值(1 2),不能解析整数我想要的是如果我输入1 2那么它将把它作为两个整数

一种选择是接受单行输入作为字符串然后处理它。 例如:

 //Read line, and split it by whitespace into an array of strings string[] tokens = Console.ReadLine().Split(); //Parse element 0 int a = int.Parse(tokens[0]); //Parse element 1 int b = int.Parse(tokens[1]); 

这种方法的一个问题是,如果用户没有以预期的格式输入文本,它将失败(通过抛出IndexOutOfRangeException / FormatException )。 如果可以,则必须validation输入。

例如,使用正则表达式:

 string line = Console.ReadLine(); // If the line consists of a sequence of digits, followed by whitespaces, // followed by another sequence of digits (doesn't handle overflows) if(new Regex(@"^\d+\s+\d+$").IsMatch(line)) { ... // Valid: process input } else { ... // Invalid input } 

或者:

  1. validation输入是否分成2个字符串。
  2. 使用int.TryParse 尝试将字符串解析为数字。

你需要类似的东西(没有错误检查代码)

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

这会读取一行,在空格上拆分并将拆分字符串解析为整数。 当然,实际上你需要检查输入的字符串是否实际上是有效整数(int.TryParse)。

然后你应该先将它存储在一个字符串中,然后使用空格作为标记将其拆分。

将该行读入字符串,拆分字符串,然后解析元素。 一个简单的版本(需要添加错误检查)将是:

 string s = Console.ReadLine(); string[] values = s.Split(' '); int a = int.Parse(values[0]); int b = int.Parse(values[1]); 
 string[] values = Console.ReadLine().Split(' '); int x = int.Parse(values[0]); int y = int.Parse(values[1]); 

在1行中,感谢LinQ和正则表达式(不需要类型检查)

 var numbers = from Match number in new Regex(@"\d+").Matches(Console.ReadLine()) select int.Parse(number.Value); 
 string x; int m; int n; Console.WriteLine("Enter two no's seperated by space: "); x = Console.ReadLine(); m = Convert.ToInt32(x.Split(' ')[0]); n = Convert.ToInt32(x.Split(' ')[1]); Console.WriteLine("" + m + " " + n); 

这应该根据您的需要工作!

 public static class ConsoleInput { public static IEnumerable ReadInts() { return SplitInput(Console.ReadLine()).Select(int.Parse); } private static IEnumerable SplitInput(string input) { return Regex.Split(input, @"\s+") .Where(x => !string.IsNullOrWhiteSpace(x)); } } 
 int a, b; string line = Console.ReadLine(); string[] numbers= line.Split(' '); a = int.Parse(numbers[0]); b = int.Parse(numbers[1]); 

试试这个:

 string numbers= Console.ReadLine(); string[] myNumbers = numbers.Split(' '); int[] myInts = new int[myNumbers.Length]; for (int i = 0; i 

希望能帮助到你:)

 using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace SortInSubSet { class Program { static int N, K; static Dictionary dicElements = new Dictionary(); static void Main(string[] args) { while (!ReadNK()) { Console.WriteLine("***************** PLEASE RETRY*********************"); } var sortedDict = from entry in dicElements orderby entry.Key/3 , entry.Value ascending select entry.Value; foreach (int ele in sortedDict) { Console.Write(ele.ToString() + " "); } Console.ReadKey(); } static bool ReadNK() { dicElements = new Dictionary(); Console.WriteLine("Please entere the No. of element 'N' ( Between 2 and 9999) and Subset Size 'K' Separated by space."); string[] NK = Console.ReadLine().Split(); if (NK.Length != 2) { Console.WriteLine("Please enter N and K values correctly."); return false; } if (int.TryParse(NK[0], out N)) { if (N < 2 || N > 9999) { Console.WriteLine("Value of 'N' Should be Between 2 and 9999."); return false; } } else { Console.WriteLine("Invalid number: Value of 'N' Should be greater than 1 and lessthan 10000."); return false; } if (int.TryParse(NK[1], out K)) { Console.WriteLine("Enter all elements Separated by space."); string[] kElements = Console.ReadLine().Split(); for (int i = 0; i < kElements.Length; i++) { int ele; if (int.TryParse(kElements[i], out ele)) { if (ele < -99999 || ele > 99999) { Console.WriteLine("Invalid Range( " + kElements[i] + "): Element value should be Between -99999 and 99999."); return false; } dicElements.Add(i, ele); } else { Console.WriteLine("Invalid number( " + kElements[i] + "): Element value should be Between -99999 and 99999."); return false; } } } else { Console.WriteLine(" Invalid number ,Value of 'K'."); return false; } return true; } } } 

我有一个更简单的解决方案,使用switch语句并在每种情况下为用户写一条消息,使用以(“\ n”)开头的Console.write()。

这是一个在获取用户输入的同时用for循环填充数组的示例。 *注意:您不需要为此工作编写for循环*尝试此示例使用名为arrayOfNumbers []的整数数组和临时整数变量。 在单独的控制台应用程序中运行此代码,并观察如何在同一行上获取用户输入!

  int temp=0; int[] arrayOfNumbers = new int[5]; for (int i = 0; i < arrayOfNumbers.Length; i++) { switch (i + 1) { case 1: Console.Write("\nEnter First number: "); //notice the "\n" at the start of the string break; case 2: Console.Write("\nEnter Second number: "); break; case 3: Console.Write("\nEnter Third number: "); break; case 4: Console.Write("\nEnter Fourth number: "); break; case 5: Console.Write("\nEnter Fifth number: "); break; } // end of switch temp = Int32.Parse(Console.ReadLine()); // convert arrayOfNumbers[i] = temp; // filling the array }// end of for loop 

这里的一个神奇技巧就是你愚弄控制台应用程序,秘诀就是你在同一行上输入用户输入你正在写你的提示信息。 (message =>“输入第一个数字:”)

这使得用户输入看起来像是插在同一行上。 我承认它有点原始,但它可以满足您的需求,而不必为复杂的代码浪费您的时间来完成这么简单的任务。