[英]Changing String input into int in C#
如何在C#代码中转换使用Console.ReadLine()函数获取的字符串输入??? 假设我创建了2个整数变量a和b。 现在我想从用户那里获取a和b的值。 如何在C#中执行此操作?
我通常使用的另一个选项是int.TryParse
int retunedInt;
bool conversionSucceed = int.TryParse("your string", out retunedInt);
因此它非常适合容错模式,例如:
if(!int.TryParse("your string", out retunedInt))
throw new FormatException("Not well formatted string");
试试这个(确保他们输入有效的字符串):
int a = int.Parse(Console.ReadLine());
这个:
int a;
string input;
do
{
input = Console.ReadLine();
} while (!int.TryParse(input, out a));
您可以将它与Int32.TryParse()
;
将数字的字符串表示形式转换为其等效的32位有符号整数。 返回值表示转换是否成功。
int i;
bool b = Int32.TryParse(yourstring, out i);
您可以使用int.TryParse
int number;
bool result = Int32.TryParse(value, out number);
TryParse方法与Parse方法类似,只是如果转换失败,TryParse方法不会抛出异常。 它消除了在s无效且无法成功解析的情况下使用异常处理来测试FormatException的需要。 参考
如果用户未键入整数,请使用Int32.TryParse以避免异常
string userInput = Console.ReadLine();
int a;
if (Int32.TryParse(userInput, out a))
Console.WriteLine("You have typed an integer number");
else
Console.WriteLine("Your text is not an integer number");
使用int.TryParse
如:
int a;
Console.WriteLine("Enter number: ");
while (!int.TryParse(Console.ReadLine(), out a))
{
Console.Write("\nEnter valid number (integer): ");
}
Console.WriteLine("The number entered: {0}", a);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.