2013-04-04 36 views
2

如何在C#代码中使用Console.ReadLine()函数转换字符串输入?假设我已经创建了2个整数变量a和b。现在我想从用户中获取a和b的值。这怎么可以在C#中执行?在C中将字符串输入更改为int#

+1

'int.Parse()'http://msdn.microsoft.com/en-gb/library/b3h1hf19.aspx。你有什么尝试? – Jodrell 2013-04-04 11:03:43

回答

2

试试这个(确保它们输入有效的字符串):

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

而且这样的:

int a; 
string input; 
do 
{ 
    input = Console.ReadLine(); 

} while (!int.TryParse(input, out a)); 
+2

'FormatException';) – Oded 2013-04-04 11:04:08

+0

你也可以使用'int.TryParse',你不确定输入是一个字符串,你想避免这个异常。 – 2013-04-04 11:04:15

9

另一种选择,我一般用的是int.TryParse

int retunedInt; 
bool conversionSucceed = int.TryParse("your string", out retunedInt); 

所以它的非常适合错误tollerant模式,如:

if(!int.TryParse("your string", out retunedInt)) 
    throw new FormatException("Not well formatted string"); 
+1

+1。出于好奇,如果你抛出异常,为什么不使用int.parse并处理可能抛出的异常呢? – keyboardP 2013-04-04 11:24:56

+0

@keyboardP:1.你可以处理一些presice(你提出的自定义异常)并继续运行程序2.你可能认为根本不使用exceptino,只是以某种方式处理流程。 – Tigran 2013-04-04 11:46:57

+0

啊,好吧,我明白了。通常我会使用'TryParse'作为第二个原因,但是我发现程序可能会有自定义的异常和日志记录,这很有用。只要确保我没有错过一些秘密的'TryParse'用法:D – keyboardP 2013-04-04 11:49:08

1

您可以使用int.TryParse

int number; 
bool result = Int32.TryParse(value, out number); 

该方法的TryParse就像解析方法,除了的TryParse 方法,如果转换失败也不会抛出异常。它 无需使用异常处理来测试 FormatException在s无效并且不能成功解析 的情况下。 Reference

1

使用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"); 
2

您可以使用Int32.TryParse();

将数字的字符串表示形式转换为其32位有符号整数等效的 。返回值指示转换 是否成功。

int i; 
bool b = Int32.TryParse(yourstring, out i); 
+1

这是在c#中转换东西的正确方法。 – Ramakrishnan 2013-04-04 11:26:44

0

使用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);