2012-09-06 69 views
1

我有點卡在這裏。雖然我知道如何將鍵盤輸入字符轉換爲C#中的可用字符。將鍵盤輸入數字轉換爲數字類型

char ch = (char)console.read(); 

我想讀取數字nd使它們在我的程序中表現爲數字。

如果我從鍵盤輸入5我希望保存爲5(數學)不是字符5.

+2

這是一個ASP.NET問題嗎?您在ASP.NET中沒有控制檯。 – slfan

回答

1

我想你想是這樣的:

int Number; 
string strNumber; 

strNumber = Console.ReadLine(); 
Number = int.Parse(strNumber); 
+0

是的確切點和重點,這是我的問題的答案。 –

1

int i = ch - '0'; //// .........

+0

+1:適用於通常的十進制數字。我相信Unicode類別_Number,Decimal Digit_包含比平時0-9更多的選項:http://www.fileformat.info/info/unicode/category/Nd/list.htm –

+2

這種方式很好,只要確保'ch> ='0'&& ch <='9''否則你會得到奇怪的結果。 –

0
string a = Console.ReadLine(); 
int b = int.Parse(a); 
Console.WriteLine(b*b); 
1

最保險的辦法會是這樣的;

int Num = 0; 

if(int.TryParse(ch.ToString(), out Num)) 
{ 
    // Num is now set correctly 
} 
else 
{ 
    // ch didn't contain a digit. 
} 
相關問題