C#字符串转int遇‘输入格式不正确’错误,求解决方案
Hey there! Let's figure out why your conversion is failing even though drivers looks like the string "11" when you print it.
The most likely culprit here is invisible hidden characters in your drivers string. Even though it prints as "11", there might be Unicode control characters, zero-width spaces, or other non-printable characters stuck in there that you can't see. These characters break Convert.ToInt32() because it expects a pure numeric string.
First, let's verify the issue
Add this code right after you print drivers.GetType() to inspect every character in the string:
foreach (char c in drivers) { Console.WriteLine($"Character: '{c}', Unicode Code: {(int)c}"); }
For the valid string "11", you should see two lines showing Character: '1', Unicode Code: 49. If you see any other codes (like 0 for null, 10 for newline, or 8203 for zero-width space), that's the hidden character causing the problem.
Fixes to try
1. Trim invisible whitespace first
Start with the simplest fix: use Trim() to remove any leading/trailing invisible characters (spaces, tabs, newlines, zero-width spaces):
int t = Convert.ToInt32(drivers.Trim());
2. Strip all non-numeric characters
If trimming doesn't work, explicitly keep only digit characters from the string:
using System.Linq; // Make sure you have this using directive at the top of your file string cleanedDrivers = new string(drivers.Where(char.IsDigit).ToArray()); if (int.TryParse(cleanedDrivers, out int t)) { Console.WriteLine($"Success! Converted value: {t}"); } else { Console.WriteLine("Still no luck - double-check the original 'result' string for odd formatting."); }
3. Use TryParse for safer conversion
Instead of Convert.ToInt32(), int.TryParse() won't crash your program and lets you handle failures gracefully:
if (int.TryParse(drivers.Trim(), out int t)) { // Conversion worked, use the value of t here Console.WriteLine($"Converted value: {t}"); } else { Console.WriteLine("Failed to convert - the string has invalid characters that aren't visible."); }
Quick check on your substring logic
It's also worth double-checking the original result string. Maybe the [[ and ]] are surrounded by extra characters, or your substring is picking up something unexpected (like hidden spaces inside the brackets). For example, if result is [[ 11 ]], your current code would grab " 11 "—Trim() would fix that, but confirming the source string helps avoid future issues.
内容的提问来源于stack exchange,提问作者Fatima

