The input string was not in a correct format の原因と直し方
int.Parseなどの変換メソッドに、数値として解釈できない文字列を渡したときに発生します。
エラーメッセージの読み方
Unhandled exception. System.FormatException: The input string 'abc' was not in a correct format.
System- 名前空間 — System なら標準の基本例外です
FormatException- 例外クラス — 何が起きたか。ここを検索するのが最短です
The input string 'abc' was not in a correct format.- 詳細メッセージ — どの値が問題だったか
at Program.Main(String[] args) in Program.cs:line 3- 発生箇所 — スタックトレースの先頭行
このエラーが出る典型パターン
パターン1
1 class Program { 2 static void Main(string[] args) { 3 int n = int.Parse("abc"); ^ 4 System.Console.WriteLine(n); 5 } 6 }
Unhandled exception. System.FormatException: The input string 'abc' was not in a correct format.
at Program.Main(String[] args) in Program.cs:line 3
int.Parseは数字だけの文字列しか変換できません。数字以外の文字が混じるとFormatExceptionになります。
直し方: "abc" を "123" にします。
広告
広告スロット(未設定)
パターン2
1 class Program { 2 static void Main(string[] args) { 3 int n = int.Parse("12.5"); ^ 4 System.Console.WriteLine(n); 5 } 6 }
Unhandled exception. System.FormatException: The input string '12.5' was not in a correct format.
at Program.Main(String[] args) in Program.cs:line 3
int.Parseは小数点を含む文字列を受け付けません。小数はdouble.Parseを使う必要があります。
直し方: "12.5" を "12" にします。
パターン3
1 class Program { 2 static void Main(string[] args) { 3 int n = int.Parse("" ); ^ 4 System.Console.WriteLine(n); 5 } 6 }
Unhandled exception. System.FormatException: The input string '' was not in a correct format.
at Program.Main(String[] args) in Program.cs:line 3
空文字列は数字を1つも含まないため、int.ParseはFormatExceptionを投げます。
直し方: "" を "7" にします。
よくある誤解
int.Parseは数字だけの文字列しか受け付けません。空文字列や小数点を含む文字列を渡すと、TryParseと違って例外で失敗を知らせます。
まとめ
The input string was not in a correct formatは初級でつまずきやすい項目です。上の3パターンを実際に手で直すと、エラーメッセージのどこを読めばよいかが掴めます。