[英]Input String is not in the correct format
我正在嘗試將文本文件中的值讀入數組。 這是一個簡單的問題,但是即使我覺得自己輸入的代碼與書中的代碼完全相同,代碼也不會運行,而不會給出錯誤“輸入字符串的格式不正確”,Visual Studio在此顯示出紙盤:
'CS_TotalSales.vshost.exe' (CLR v4.0.30319: CS_TotalSales.vshost.exe): Loaded 'c:\users\dakota\documents\visual studio 2013\Projects\CS_TotalSales\CS_TotalSales\bin\Debug\CS_TotalSales.exe'. Symbols loaded.
'CS_TotalSales.vshost.exe' (CLR v4.0.30319: CS_TotalSales.vshost.exe): Loaded 'C:\Windows\Microsoft.Net\assembly\GAC_MSIL\Accessibility\v4.0_4.0.0.0__b03f5f7f11d50a3a\Accessibility.dll'. Cannot find or open the PDB file.
A first chance exception of type 'System.FormatException' occurred in mscorlib.dll
我不確定上述任何含義,盡管我想知道我的書中是否有錯字。 下面是代碼,什么可能導致此錯誤?
//declare array and size variables
const int SIZE = 7;
decimal[] salesArray = new decimal[SIZE];
//declare a counter
int index = 0;
try
{
//decalre and initialize a streamreader object for the sales file
StreamReader inputFile = File.OpenText("Sales.txt");
while (index < salesArray.Length && !inputFile.EndOfStream)
{
salesArray[index] = int.Parse(inputFile.ReadLine());
index++;
}
//close the file
inputFile.Close();
//add sales to listbox
foreach (int sale in salesArray)
{
salesListbox.Items.Add(sale);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
這行是引起異常的行:
salesArray[index] = int.Parse(inputFile.ReadLine());
輸入文件Sales.txt
中至少有一行不能解析為整數。 可能是空行,或者是一些多余的字符,使其成為無效的整數。 也許有一個帶點的數字(不是整數)或其他。
請改用TryParse()
方法,並檢查嘗試解析該行是否出錯。 嘗試更改此位:
int number;
while (index < salesArray.Length && !inputFile.EndOfStream)
{
if (Int32.TryParse(inputFile.ReadLine(), out number))
salesArray[index++] = number;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.