2016-01-22 17 views
-3

我知道對於使用Convert.To方法讀取輸入,但是除此之外還有什麼方法可以讀取。在C中讀取整數的替代方案#

int k = Convert.ToInt16(Console.ReadLine()); 
+0

不這樣做你想要什麼? – HimBromBeere

+2

實際上你應該使用'Convert.ToInt32'。還有'int.Parse'。 –

+0

是的,但我想要的是有任何其他方法 –

回答

5

要從控制檯應用程序讀取輸入的最簡單方法是Console.ReadLine。有可能的替代方案,但它們更復雜,並預留給特殊情況:請參閱Console.ReadConsole.ReadKey

什麼是多麼重要的是轉換不應該使用Convert.ToInt32Int32.ParseInt32.TryParse

int k = 0; 
string input = Console.ReadLine(); 
if(Int32.TryParse(input, out k)) 
    Console.WriteLine("You have typed a valid integer: " + k); 
else 
    Console.WriteLine("This: " + input + " is not a valid integer"); 

之所以用Int32.TryParse謊言在事實,你可以檢查完成的整數倍轉換爲整數是可能的或不可以。其他方法反而會引發一個異常,您應該處理複雜的代碼流。

+1

你有編譯時間錯誤,因爲'k'變量沒有被初始化。另外'Console.WriteLine(「This:」+ k +「不是一個有效的整數」);'不顯示wrond用戶的輸入 – Michael

+0

你當然是正確的。不直截了當,在我的辯護中,我可以說我把Console.WriteLine與k值作爲事後的想法,只是爲了顯示錯誤 – Steve

1

可以使用int.TryParse

見例如

var item = Console.ReadLine(); 
int input; 
if (int.TryParse(item, out input)) 
{ 
    // here you got item as int in input variable. 
    // do your stuff. 
    Console.WriteLine("OK"); 
} 
else 
    Console.WriteLine("Entered value is invalid"); 

Console.ReadKey(); 
1

這是一種替代和最佳method,你可以遵循:

int k; 
if (int.TryParse(Console.ReadLine(), out k)) 
    { 
     //Do your stuff here 
    } 
else 
    { 
     Console.WriteLine("Invalid input"); 
    } 
3

您可以創建自己的實現了控制檯和使用它隨處可見:

public static class MyConsole 
{ 
    public static int ReadInt() 
    { 
     int k = 0; 
     string val = Console.ReadLine(); 
     if (Int32.TryParse(val, out k)) 
      Console.WriteLine("You have typed a valid integer: " + k); 
     else 
      Console.WriteLine("This: " + val + " is not a valid integer"); 
     return k; 
    } 

    public static double ReadDouble() 
    { 
     double k = 0; 
     string val = Console.ReadLine(); 
     if (Double.TryParse(val, out k)) 
      Console.WriteLine("You have typed a valid double: " + k); 
     else 
      Console.WriteLine("This: " + val + " is not a valid double"); 
     return k; 
    } 
    public static bool ReadBool() 
    { 
     bool k = false; 
     string val = Console.ReadLine(); 
     if (Boolean.TryParse(val, out k)) 
      Console.WriteLine("You have typed a valid bool: " + k); 
     else 
      Console.WriteLine("This: " + val + " is not a valid bool"); 
     return k; 
    } 
} 

class Program 
{ 
    static void Main(string[] args) 
    { 
     int s = MyConsole.ReadInt(); 
    } 

} 
+0

就像是用戶定義的函數 –

+0

這些只是用戶定義的函數) – Michael

+0

好的,謝謝@ VMA –

1

有3種類型的整數:

1)Short Integer:16位數字(-32768到32767)。在c#中,您可以聲明一個短整型變量,如shortInt16

2.)"Normal" Integer:32位數(-2147483648至2147483647)。用關鍵字intInt32聲明一個整數。

3.)Long Integer:64位數字(-9223372036854775808至9223372036854775807)。用longInt64聲明一個長整數。

區別在於您可以使用的數字範圍。 您可以使用Convert.ToParseTryParse將其轉換。