C# 如果两个输入用空格分隔,如何从用户处获取输入?
在两个输入被空格分隔的情况下,如何从用户处获取输入? 我试着用Conver.ToInt32(Console.ReadLine())来实现这一点;但它显示了格式异常。 请告知是否有其他方式从用户处获取输入。 请帮忙! 谢谢你阅读我的问题 例: 输入: 10 2 输入为上述格式。 值10和2应存储在不同的变量中。C# 如果两个输入用空格分隔,如何从用户处获取输入?,c#,C#,在两个输入被空格分隔的情况下,如何从用户处获取输入? 我试着用Conver.ToInt32(Console.ReadLine())来实现这一点;但它显示了格式异常。 请告知是否有其他方式从用户处获取输入。 请帮忙! 谢谢你阅读我的问题 例: 输入: 10 2 输入为上述格式。 值10和2应存储在不同的变量中。Console.ReadLine()仅在用户输入新行(即按return)时返回值 string[] inputs =Console.ReadLine().Split(null); int
Console.ReadLine()
仅在用户输入新行(即按return)时返回值
string[] inputs =Console.ReadLine().Split(null);
int input1=TryParse(inputs[0]);
int input2=TryParse(inputs[1]);
为了得到你想要的,你可以考虑使用<代码>控制台。 使您的代码看起来像:
public int GetNextNumber()
{
char nextChar;
string numberString = string.Empty;
while (!char.IsWhiteSpace(nextChar = (char)Console.Read())
numberString += nextChar;
int result;
if (!int.TryParse(numberString, out result))
throw new InvalidCastException("Specified string is not an integral");
return result;
}
int input = Convert.ToInt32(Console.ReadLine());
然后,当用户输入时,您可以使用该方法从控制台读取每个单独的数字。
您还可以执行一个Console.ReadLine()
并拆分生成的字符串,以获得与建议的其他字符串类似的数字
希望这能有所帮助。因为我看不到您尝试的实际代码,我可以假设您做了如下操作:
public int GetNextNumber()
{
char nextChar;
string numberString = string.Empty;
while (!char.IsWhiteSpace(nextChar = (char)Console.Read())
numberString += nextChar;
int result;
if (!int.TryParse(numberString, out result))
throw new InvalidCastException("Specified string is not an integral");
return result;
}
string[] inputs =TextBoX1.Text.Split(" ");
String first = inputs[0].ToString();
String second = inputs[1].ToString();
int input = Convert.ToInt32(Console.ReadLine());
而实际的输入是“102”,这是一个字符串。
当该方法尝试将空空间转换为int时出错
您需要将输入保存为字符串变量,然后使用空格分隔字符串变量。您可以将结果保存为字符串数组(字符串[]),然后将字符串[]的每个数组元素转换为int
读取代码的输入:
string input = Console.Readline();
string[] stringArray= input.Split(' ');
List<int> integerList = new List<int>();
foreach (string str in array)
{
integerList.Add(Convert.ToInt32(str));
}
代码的拆分方法:
string input = Console.Readline();
string[] stringArray= input.Split(' ');
List<int> integerList = new List<int>();
foreach (string str in array)
{
integerList.Add(Convert.ToInt32(str));
}
将代码的每个字符串转换为int:
string input = Console.Readline();
string[] stringArray= input.Split(' ');
List<int> integerList = new List<int>();
foreach (string str in array)
{
integerList.Add(Convert.ToInt32(str));
}
List integerList=newlist();
foreach(数组中的字符串str)
{
integerList.Add(Convert.ToInt32(str));
}
请注意,这也适用于具有2个以上数字的输入,例如“10 2 17 3 19 27”,并且每个输入部分不需要自己的变量,因为您将每个值添加到列表中。为什么要列出清单?因为大小是动态的。您的问题也会出现在数组而不是列表上,因为在拆分字符串时,您知道数组需要的大小,但列表更合适。将输入作为字符串读入并用空格拆分。我猜想问题不是从用户处获取输入,而是将其解析为两个变量?可能是重复的你能扩展你的答案,包括对你的代码的解释吗?它对读者的帮助比你想象的要多。