2013-04-04 65 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);