【发布时间】:2010-10-07 12:56:00
【问题描述】:
我知道如何让控制台读取两个整数,但每个整数都是这样的
int a = int.Parse(Console.ReadLine());
int b = int.Parse(Console.ReadLine());
如果我输入了两个数字,即 (1 2),则值 (1 2) 无法解析为整数 我想要的是如果我输入 1 2 那么它将把它当作两个整数
【问题讨论】:
标签: c# parsing console integer
我知道如何让控制台读取两个整数,但每个整数都是这样的
int a = int.Parse(Console.ReadLine());
int b = int.Parse(Console.ReadLine());
如果我输入了两个数字,即 (1 2),则值 (1 2) 无法解析为整数 我想要的是如果我输入 1 2 那么它将把它当作两个整数
【问题讨论】:
标签: c# parsing console integer
一种选择是接受单行输入作为字符串,然后对其进行处理。 例如:
//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)。如果可能,您必须验证输入。
例如,使用正则表达式:
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
}
或者:
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<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));
}
}
【讨论】:
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<myInts.Length; i++)
{
string myString=myNumbers[i].Trim();
myInts[i] = int.Parse(myString);
}
希望对你有帮助:)
【讨论】:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SortInSubSet
{
class Program
{
static int N, K;
static Dictionary<int, int> dicElements = new Dictionary<int, int>();
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<int, int>();
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=>"输入第一个数字:")
这使得用户输入看起来像是被插入到同一行。我承认这有点原始,但它可以满足您的需求,而不必为如此简单的任务浪费时间编写复杂的代码。
【讨论】: