C# 从用户输入读取整数
我要寻找的是如何从命令行(控制台项目)读取用户给定的整数。我主要知道C++,并且已经开始了C路径。我知道那个控制台;只接受一个字符/字符串。简而言之,我在寻找这个的整数版本 让你知道我到底在做什么:C# 从用户输入读取整数,c#,input,C#,Input,我要寻找的是如何从命令行(控制台项目)读取用户给定的整数。我主要知道C++,并且已经开始了C路径。我知道那个控制台;只接受一个字符/字符串。简而言之,我在寻找这个的整数版本 让你知道我到底在做什么: Console.WriteLine("1. Add account."); Console.WriteLine("Enter choice: "); Console.ReadLine(); // Needs to take in int rather than string or char. 我已
Console.WriteLine("1. Add account.");
Console.WriteLine("Enter choice: ");
Console.ReadLine(); // Needs to take in int rather than string or char.
我已经找了很长时间了。我在C上找到了很多东西,但没有找到C。不过,我在另一个网站上发现了一个线程,它建议将char转换为int。我确信,必须有一种比转换更直接的方法 您可以使用函数将字符串转换为整数
您需要对输入进行类型转换。尝试使用以下命令
int input = Convert.ToInt32(Console.ReadLine());
如果值不是数字,它将引发异常
编辑
我知道上面是一个快速的例子。我想改进我的回答:
String input = Console.ReadLine();
int selectedOption;
if(int.TryParse(input, out selectedOption))
{
switch(selectedOption)
{
case 1:
//your code here.
break;
case 2:
//another one.
break;
//. and so on, default..
}
}
else
{
//print error indicating non-numeric input is unsupported or something more meaningful.
}
我建议您使用
TryParse
:
Console.WriteLine("1. Add account.");
Console.WriteLine("Enter choice: ");
string input = Console.ReadLine();
int number;
Int32.TryParse(input, out number);
这样,如果您试图解析“1q”或“23e”之类的内容,因为有人输入了错误,您的应用程序就不会抛出异常
Int32.TryParse
返回一个布尔值,因此您可以在if
语句中使用它,以查看是否需要对代码进行分支:
int number;
if(!Int32.TryParse(input, out number))
{
//no, not able to parse, repeat, throw exception, use fallback value?
}
对于您的问题:您将找不到读取整数的解决方案,因为ReadLine()
读取整个命令行,threfor返回一个字符串。您可以做的是,尝试将此输入转换为和int16/32/64变量
为此,有几种方法:
if(Int32.TryParse(input, out int number))
{
/* Yes input could be parsed and we can now use number in this code block
scope */
}
else
{
/* No, input could not be parsed to an integer */
}
完整的示例如下所示:
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
var foo = Console.ReadLine();
if (int.TryParse(foo, out int number1)) {
Console.WriteLine($"{number1} is a number");
}
else
{
Console.WriteLine($"{foo} is not a number");
}
Console.WriteLine($"The value of the variable {nameof(number1)} is {number1}");
Console.ReadLine();
}
}
在这里您可以看到,即使输入不是一个数字,变量
number1
也会被初始化,并且不管输入值是多少都是0,因此即使在声明if块之外它也是有效的更好的方法是使用TryParse:
Int32 _userInput;
if(Int32.TryParse (Console.Readline(), out _userInput) {// do the stuff on userInput}
您可以继续尝试:
Console.WriteLine("1. Add account.");
Console.WriteLine("Enter choice: ");
int choice=int.Parse(Console.ReadLine());
这应该适用于案例陈述
它与switch语句一起工作,不会引发异常。我使用了
int intTemp=Convert.ToInt32(Console.ReadLine())代码>而且效果很好,下面是我的示例:
int balance = 10000;
int retrieve = 0;
Console.Write("Hello, write the amount you want to retrieve: ");
retrieve = Convert.ToInt32(Console.ReadLine());
对于你的问题,我没有看到一个好的完整的答案,所以我将展示一个更完整的例子。有一些方法展示了如何从用户那里获取整数输入,但是每当你这样做的时候,你通常也需要这样做
验证输入
如果输入无效,则显示错误消息
已给出,并且
循环直到给出有效的输入
此示例显示如何从用户处获取等于或大于1的整数值。如果提供的输入无效,它将捕获错误,显示错误消息,并请求用户重试以获得正确的输入
static void Main(string[] args)
{
int intUserInput = 0;
bool validUserInput = false;
while (validUserInput == false)
{
try
{ Console.Write("Please enter an integer value greater than or equal to 1: ");
intUserInput = int.Parse(Console.ReadLine()); //try to parse the user input to an int variable
}
catch (Exception) { } //catch exception for invalid input.
if (intUserInput >= 1) //check to see that the user entered int >= 1
{ validUserInput = true; }
else { Console.WriteLine("Invalid input. "); }
}//end while
Console.WriteLine("You entered " + intUserInput);
Console.WriteLine("Press any key to exit ");
Console.ReadKey();
}//end main
在您的问题中,您似乎想将其用于菜单选项。因此,如果您想通过选择菜单选项获得int输入,可以将if语句更改为
if ( (intUserInput >= 1) && (intUserInput <= 4) )
if((intUserInput>=1)和&(intUserInputstatic void Main(字符串[]args)
{
Console.WriteLine(“请输入1到10之间的数字”);
int counter=Convert.ToInt32(Console.ReadLine());
//这是您的变量
Console.WriteLine(“数字从开始”);
做
{
计数器++;
控制台。写入(计数器+“,”);
}而(计数器<100);
Console.ReadKey();
}
用这句简单的话:
int x = int.Parse(Console.ReadLine());
尝试此操作,它不会引发异常,用户可以重试:
Console.WriteLine("1. Add account.");
Console.WriteLine("Enter choice: ");
int choice = 0;
while (!Int32.TryParse(Console.ReadLine(), out choice))
{
Console.WriteLine("Wrong input! Enter choice number again:");
}
您可以创建自己的ReadInt函数,该函数只允许数字
(此功能可能不是进行此操作的最佳方式,但可以完成此工作)
公共静态int ReadInt()
{
字符串allowedChars=“0123456789”;
ConsoleKeyInfo read=新建ConsoleKeyInfo();
List outInt=新列表();
而(!(read.Key==ConsoleKey.Enter&&outit.Count>0))
{
read=Console.ReadKey(真);
if(allowedChars.Contains(read.KeyChar.ToString()))
{
outInt.Add(read.KeyChar);
Console.Write(read.KeyChar.ToString());
}
if(read.Key==ConsoleKey.Backspace)
{
如果(outInt.Count>0)
{
outit.RemoveAt(outit.Count-1);
Console.CursorLeft--;
控制台。写(“”);
Console.CursorLeft--;
}
}
}
Console.SetCursorPosition(0,Console.CursorTop+1);
返回int.Parse(新字符串(outInt.ToArray());
}
简单方法int a=int.Parse(Console.ReadLine());令人惊讶的是,我以前尝试过这个方法,但没有成功。但只是再次尝试,它成功了…感谢Console.WriteLine(“1.添加帐户”);Console.WriteLine(“输入选项:”;int-choice=Convert.ToInt32(Console.ReadLine());if(选项==1)//依此类推。这有效。将标记为答案。此答案完全错误。如果用户输入不是数字,则Convert.ToInt32或Int32.Parse将失败,并出现异常。当无法保证输入是数字时,请始终使用Int32.TryParse。我想您不会有整数版本的ReadLine
,您应该保留返回值在string
中,尝试将其转换为int
(可以Int32.TryParse
或其他带有try/catch
的ans),如果输入项不是int
,则提示用户再试一次。更好的方法是在字符串变量中输入,然后使用int.TryParse
进行conversion.Upvote。int.TrypParse
是更好的解决方案@
static void Main(string[] args)
{
Console.WriteLine("Please enter a number from 1 to 10");
int counter = Convert.ToInt32(Console.ReadLine());
//Here is your variable
Console.WriteLine("The numbers start from");
do
{
counter++;
Console.Write(counter + ", ");
} while (counter < 100);
Console.ReadKey();
}
int x = int.Parse(Console.ReadLine());
Console.WriteLine("1. Add account.");
Console.WriteLine("Enter choice: ");
int choice = 0;
while (!Int32.TryParse(Console.ReadLine(), out choice))
{
Console.WriteLine("Wrong input! Enter choice number again:");
}
public static int ReadInt()
{
string allowedChars = "0123456789";
ConsoleKeyInfo read = new ConsoleKeyInfo();
List<char> outInt = new List<char>();
while(!(read.Key == ConsoleKey.Enter && outInt.Count > 0))
{
read = Console.ReadKey(true);
if (allowedChars.Contains(read.KeyChar.ToString()))
{
outInt.Add(read.KeyChar);
Console.Write(read.KeyChar.ToString());
}
if(read.Key == ConsoleKey.Backspace)
{
if(outInt.Count > 0)
{
outInt.RemoveAt(outInt.Count - 1);
Console.CursorLeft--;
Console.Write(" ");
Console.CursorLeft--;
}
}
}
Console.SetCursorPosition(0, Console.CursorTop + 1);
return int.Parse(new string(outInt.ToArray()));
}