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

料青山看我應(yīng)如是
TA貢獻(xiàn)1772條經(jīng)驗(yàn) 獲得超8個贊
您可以使用Convert.ToInt32()函數(shù)將字符串轉(zhuǎn)換為整數(shù)
int intTemp = Convert.ToInt32(Console.ReadLine());

收到一只叮咚
TA貢獻(xiàn)1821條經(jīng)驗(yàn) 獲得超5個贊
您需要對輸入進(jìn)行類型轉(zhuǎn)換。嘗試使用以下內(nèi)容
int input = Convert.ToInt32(Console.ReadLine());
如果值為非數(shù)字,它將拋出異常。
編輯
我知道上面的內(nèi)容很快。我想改進(jìn)我的答案:
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 關(guān)注
- 637 瀏覽
添加回答
舉報
0/150
提交
取消