從用戶輸入中讀取整數我正在尋找的是如何讀取用戶從命令行(控制臺項目)給出的整數。我主要了解C ++并且已經開始了C#路徑。我知道Console.ReadLine(); 只接受一個字符串/字符串。所以總之我正在尋找這個的整數版本。只是為了讓你了解我正在做的事情:Console.WriteLine("1. Add account.");Console.WriteLine("Enter choice: ");Console.ReadLine(); // Needs to take in int rather than string or char.我一直在尋找這個。我在C上找到了很多但不是C#。我確實在另一個網站上找到了一個建議從char轉換為int的線程。我確信必須有比轉換更直接的方式。
3 回答

至尊寶的傳說
TA貢獻1789條經驗 獲得超10個贊
您需要對輸入進行類型轉換。嘗試使用以下內容
int input = Convert.ToInt32(Console.ReadLine());
如果值為非數字,它將拋出異常。
編輯
我知道上面的內容很快。我想改進我的答案:
String input = Console.ReadLine();int selectedOption;if(int.TryParse(input, out selectedOption)){ switch(selectedOption) { case 1: //your code here. break; case 2: //another one. break; //. and so on, default.. }} else{ //print error indicating non-numeric input is unsupported or something more meaningful.}
- 3 回答
- 0 關注
- 395 瀏覽
添加回答
舉報
0/150
提交
取消