在C#中,為了避免使用scanf
時(shí)可能遇到的輸入錯(cuò)誤,你可以采用以下方法:
Console.ReadLine()
方法讀取整行輸入,然后使用int.TryParse()
方法嘗試將輸入轉(zhuǎn)換為整數(shù)。這樣可以確保輸入的值是一個(gè)有效的整數(shù),并在轉(zhuǎn)換失敗時(shí)提供有用的錯(cuò)誤信息。示例代碼:
using System;
class MainClass {
public static void Main (string[] args) {
int number;
string input = Console.ReadLine();
if (int.TryParse(input, out number)) {
Console.WriteLine("You entered the number: " + number);
} else {
Console.WriteLine("Invalid input. Please enter a valid integer.");
}
}
}
try-catch
語(yǔ)句捕獲可能的異常,例如FormatException
。這樣,當(dāng)輸入無(wú)效時(shí),程序不會(huì)崩潰,而是會(huì)顯示一條錯(cuò)誤消息。示例代碼:
using System;
class MainClass {
public static void Main (string[] args) {
try {
int number = int.Parse(Console.ReadLine());
Console.WriteLine("You entered the number: " + number);
} catch (FormatException) {
Console.WriteLine("Invalid input. Please enter a valid integer.");
}
}
}
這兩種方法都可以幫助你避免輸入錯(cuò)誤,并提供更好的用戶體驗(yàn)。