Dlorwisdom
Dlorwisdom

Reputation: 117

Input String is not in the correct format

I am trying to read values from a text file into an array. This is a simple issue but even though I feel as though I've typed the code exactly as it is in my book, the code will not run without giving the error "input string is not in the right format" visual studio shows this in the output tray:

'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

I am unsure what any of the above means, although Im wondering if perhaps there has been a typo in my book. Below is the code, what could cause this error?

 //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);
            }

Upvotes: 0

Views: 1722

Answers (1)

Leandro
Leandro

Reputation: 1555

This line is the one causing the exception:

salesArray[index] = int.Parse(inputFile.ReadLine());

There is at least one line in your input file Sales.txt which cannot be parsed as an integer. Maybe a blank line, or some extra characters which make it an invalid integer. Perhaps there is a number with a dot (not an integer) or something else.

Use the TryParse() method instead, and check if there was an error in attempting to parse the line. Try changing this bit:

int number;
while (index < salesArray.Length && !inputFile.EndOfStream)
{
     if (Int32.TryParse(inputFile.ReadLine(), out number))
        salesArray[index++] = number;
}

Upvotes: 1

Related Questions