Where does this error come from when converting from string to int in C #?
Closed due to the fact that off-topic participants Grundy , αλεχολυτ , PashaPash ♦ 24 Nov '16 at 16:50 .
It seems that this question does not correspond to the subject of the site. Those who voted to close it indicated the following reason:
- “Questions asking for help with debugging (“ why does this code not work? ”) Should include the desired behavior, a specific problem or error, and a minimum code for playing it right in the question . Questions without an explicit description of the problem are useless for other visitors. See How to create minimal, self-sufficient and reproducible example . " - Grundy, αλεχολυτ, PashaPash
- 3Show the conversion code. And look at the data in the debugger - Zufir
- oneWhat exactly is not clear in the line: The input line had the wrong format ? - Grundy
- If you are given an exhaustive answer, mark it as correct (tick the selected answer). - andreycha
2 answers
This error occurs if the string does not contain a number. To softly convert a string to a number, use the TryParse() method:
int number; bool result = int.TryParse("42", out number); // true int number2; bool result2 = int.TryParse("ololo42", out number2); // false - most likely there
.instead of,or vice versa in the number. - Grundy - @Grundy in int'e no separator) - Trymount
- @Trymount, another reason for the error :) - Grundy
The input string had the wrong format - it means that you are trying to convert a character string to an integer, while in the original character string not all characters are numbers. In order to figure out what went wrong - just look at what you pass to the conversion method. For example:
string inputStr = "123a56"; int number; bool isNumeric = int.TryParse(inputStr, out number); if(isNumeric) { Console.WriteLine("Строка успешно преобразована в число"); } else { Console.WriteLine("Ошибка преобразования. Вы уверены, что '" + inputStr + "' число?"); } The error associated with the DateTime may be falling because the input string is a composite format. This composite format is built incorrectly and looks like a date. And you were rightly told to use the Int32.TryParse Method .
Useful links for familiarization:
- FormatException
- Composite Formatting
- Method you use Int32.Parse Method (most likely)
If you want to use Int32.Parse , then the problem can be solved like this:
string inputStr = "123a56"; try { int number = Int32.Parse(inputStr); Console.WriteLine("Строка успешно преобразована в число"); } catch(Exception ex) { Console.WriteLine("Ошибка преобразования. Вы уверены, что '" + inputStr + "' число?"); } You can read about try-catch here:
