C# 输入字符串的格式不正确

C# 输入字符串的格式不正确,c#,visual-studio-2013,C#,Visual Studio 2013,我试图将值从文本文件读入数组。这是一个简单的问题,但尽管我觉得我键入的代码与我的书中的代码完全相同,但如果不给出错误“输入字符串格式不正确”,代码将无法运行 visual studio在输出托盘中显示以下内容: 'CS_TotalSales.vshost.exe' (CLR v4.0.30319: CS_TotalSales.vshost.exe): Loaded 'c:\users\dakota\documents\visual studio 2013\Projects\CS_TotalSal

我试图将值从文本文件读入数组。这是一个简单的问题,但尽管我觉得我键入的代码与我的书中的代码完全相同,但如果不给出错误“输入字符串格式不正确”,代码将无法运行 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);
            }
//声明数组和大小变量
常数int SIZE=7;
十进制[]salesArray=新的十进制[大小];
//申报柜台
int指数=0;
尝试
{
//重新标记并初始化销售文件的streamreader对象
StreamReader inputFile=File.OpenText(“Sales.txt”);
while(索引
这一行是导致异常的那一行:

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;
}
整数;
while(索引
检查源文件。将抛出
系统.FormatException
错误。您可能有一行带有尾随空格或行中的某些内容。
salesArray[index]=int.Parse(inputFile.ReadLine())尝试将此行更改为
salesaray[index]=Convert.ToInt32(inputFile.ReadLine().Trim())像@弥敦说,如果是这样的话,请考虑从代码< >输入文件.RealLoad()/<代码>中修剪返回值。您可以在文件中显示相同的示例数据吗?如果您在解析过程中设置一个尝试catch,您将能够输出导致问题的行。还考虑使用(流读取器)代替手动关闭流。我试图添加的数字中有小数点!!小数点是导致异常的原因!我没想到!非常感谢。