2014-10-04 133 views
1

我是C#的新手,並且正在處理文本格式。我稍微離開了課程計劃以格式化用戶輸入的電話號碼。雖然程序編譯並運行,但輸入內容時會崩潰。C#ReadLine轉換問題

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 

namespace Strings 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      int PhoneNumber = Convert.ToInt32(Console.ReadLine()); 

      string myString = string.Format("Phone Number: {0:(###) ###-####}", PhoneNumber); 

      Console.WriteLine(myString); 
      Console.ReadLine(); 
     } 
    } 
} 

回答

1

與您的代碼的問題是,對於intInt32)最大值爲2147483647,這可能比你自己輸入的電話號碼,使其與OverflowException崩潰較少。

變化intlong

long PhoneNumber = Convert.ToInt64(Console.ReadLine()); 

string myString = string.Format("Phone Number: {0:(###) ###-####}", PhoneNumber); 

Console.WriteLine(myString); 
Console.ReadLine(); 

但我建議您閱讀並保持在string的電話號碼,因爲一個整數並沒有真正意義的數據類型。

+0

感謝您的幫助。事情是:我最初嘗試使用這個字符串,但它不會使用格式。我假設只有格式類型除了整數? – Mbdelta 2014-10-04 05:03:24