locked
Input string was not in a correct format -Problem

    Question

  • Alright well I'm extremely new to programming so odds are this is a really easy fix but for some reason im receiving a "Input string was not in a correct format." error  when i try to parse a string value from a file to double when I'm pretty sure the string being input is definitely a number that can be parsed to double. Thanks in advance!!

    Here's the code for the method that I'm getting the error from:

    I receive the error "Input string was not in a correct format." at the line that says "annualInterestRate = Double.Parse(inFile.ReadLine());"                                                                                                         

    public static void LoadArray(SavingsAccount [ ] array)
            {
                string accountHolder = " ";
                string accountNumber = " ";
                double annualInterestRate = 0.0;
                double savingsBalance = 0.0;
                int i = 0;



                StreamReader inFile = new StreamReader(@"C:\Users\Juan D Sanchez\Desktop\accountdata.txt");


                SavingsAccount account1 = new SavingsAccount();


                //set array values to default constructor
                for (int j = 0; j < array.Length; j++)
                    array[j] = new SavingsAccount();


                while (inFile.ReadLine() != null)
                {
                    //input file
                    annualInterestRate = Double.Parse(inFile.ReadLine());
                    savingsBalance = Double.Parse(inFile.ReadLine());
                    accountNumber = inFile.ReadLine();
                    accountHolder = inFile.ReadLine();

                    //set info from input file
                    account1.setAccountNumber(accountNumber);
                    account1.setAccountHolder(accountHolder);
                    account1.ModifyInterestRate(annualInterestRate);
                    account1.ModifySavingsBalance(savingsBalance);


                    array[i] = new SavingsAccount(annualInterestRate, savingsBalance, accountNumber, accountHolder);
                    i++;
                }
            }

    If the error has to to do with the input file, here is the exact data in the exact format that i have it in the file. As you see the first number is "0.015" so i don't see why that cant be converted to a double:

    0.015 2000 w8v6754r6 Jacobs,Michael 
    0.045 60000 w4fg55566 Ray,Bill 
    0.035 40000 w6gyhygg7 Nichols,Luke 
    0.018 25000 w5g55g777 Hendricks,Gary

    Again, I'm a beginner  and this is my first time posting so let me know if your need more of the code or something, thanks!

    Tuesday, February 14, 2012 7:21 PM

Answers

  • Well this is strange. I went through and checked the array and everything filled out perfectly. Array indexes 0 through 3 filled with all the info from the input file and the rest of the array stayed with the default values that it had. So technically, it looks like everything worked, just for some reason, its bringing up this eror. Could it be that the program is looping again even though there are no more values in the input file?
    Perhaps there's a blank line at the end of the input file or something?
    Wednesday, February 15, 2012 8:26 AM
  • Hi jsanch16,

    Welcome to the MSDN forum!

    How is it going with the problem?

    I agree with Matthew' opinion on that there might be some "blank" value for the fields, according to the debug result you have showed for us. 

    Name:              Value:

    fields              {string [1]}

    [0]           "" 

    Perhaps you need to check the content of your text file first and try the following code:

            static void teststring()
            {
                StreamReader infile = new StreamReader(@"E:\test.txt");  
                 while (!infile.EndOfStream)
                {
                     string[] fields = infile.ReadLine().Trim().Split(' ');
                     foreach(string s in fields)
                     {
                         if (s !=string.Empty) // Check first!
                         {
                             Console.WriteLine(s);
                         }
                     }
                 }
            }

    Below is the original text file:

    If don't check the string first, I get the following result:

    Hope it helps.

    Thanks.


    Yoyo Jiang[MSFT]
    MSDN Community Support | Feedback to us

    Thursday, February 16, 2012 8:29 AM
  • I think you're finding something inevitable -- when processing raw I/O like this you should really always  have some sort of validation.  A couple of points to start with:

    1. You may want to add the StringSplitOptions.RemoveEmptyEntries argument when you split the string, that way multiple spaces between values will get collapsed.
    2. Validate each array of pieces (the array I called "fields") for length
    3. To be really robust, use the double.TryParse method to check whether the first two chunks are really numbers.

    Also, you've got some other issues in your program:

    • You create an account1 object and change the values on every single iteration, but then never actually use it.
    • You fill your array with new Acounts but then overwrite them with other new accounts in the loop. Unless this stuff is in there purely for testing purposes, remove it.
    • You never do any array resizing or bounds checking, so it's quite likely that the array you have provided is not the correct length. You should address this.
    • You never closed your stream! I'll recommend you use a using block, especially since errors may occur while the stream is open

    Maybe this can get you started on the right track of proper data validation, and the other points:

        public static void LoadArray(SavingsAccount[] array) {
            string accountHolder = " ";
            string accountNumber = " ";
            double annualInterestRate = 0.0;
            double savingsBalance = 0.0;
            Array.Resize(ref array, 0); // Erase elements of existing array
    
            using (StreamReader inFile = new StreamReader(@"C:\Users\Juan D Sanchez\Desktop\accountdata.txt")) {
                int i = 0;
                while (!inFile.EndOfStream) {
                    string[] fields = inFile.ReadLine().Trim()
                                        .Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
    
                    if (fields.Length == 0) {
                        //Emtpy line. Skip it and continue.
                    }
                    else if (fields.Length == 4) {
                        if (!double.TryParse(fields[0], out annualInterestRate)) {
                            throw new ArgumentException("Cannot parse value '" + fields[0] + "' as a double");
                        }
                        if (!double.TryParse(fields[1], out savingsBalance)) {
                            throw new ArgumentException("Cannot parse value '" + fields[1] + "' as a double");
                        }
                        accountNumber = fields[2];
                        accountHolder = fields[3];
    
                        Array.Resize(ref array, i + 1);
                        array[i] = new SavingsAccount(annualInterestRate, savingsBalance, accountNumber, accountHolder);
                        i++;
                    }
                    else {
                        throw new IndexOutOfRangeException("Input string does not have the right number of fields!");
                    }
                }
                inFile.Close();
            }
        }


    jmh

    Thursday, February 16, 2012 3:40 PM

All replies

  • Every time you call .ReadLine() you are, well, reading an entire line. So you are essentially doing this:

        while ("0.015 2000 w8v6754r6 Jacobs,Michael" != null) {
                //input file
                annualInterestRate = Double.Parse("0.045 60000 w4fg55566 Ray,Bill");
                savingsBalance = Double.Parse("0.035 40000 w6gyhygg7 Nichols,Luke");
                accountNumber = "0.018 25000 w5g55g777 Hendricks,Gary";
                accountHolder = ??
                ...
        }

    What you're trying to do is

        while (!inFile.EndOfStream ) {
            string[] fields = inFile.ReadLine().Trim().Split(' ');
            annualInterestRate = Double.Parse(fields[0]);
            savingsBalance = Double.Parse(fields[1]);
            accountNumber = fields[2];
            accountHolder = fields[3];
            ...
        }

    For further learning, check out:

    And for something really helpful in this situation, take a look at the TextFieldParser Class. It's in the Visual Basic assembly, but you can still use it from C#.


    jmh


    Tuesday, February 14, 2012 7:29 PM
  • I'm still getting the same error. I implemented your code and I'm gettin the "input string not in the correct format error" at "annualInterestRate = Double.Parse(fields[0]);"

    Heres the code now:

     public static void LoadArray(SavingsAccount [ ] array)
            {
                string accountHolder = " ";
                string accountNumber = " ";
                double annualInterestRate = 0.0;
                double savingsBalance = 0.0;
                int i = 0;
                


                StreamReader inFile = new StreamReader(@"C:\Users\Juan D Sanchez\Desktop\accountdata.txt");


                SavingsAccount account1 = new SavingsAccount();


                //set to default constructor
                for (int j = 0; j < array.Length; j++)
                    array[j] = new SavingsAccount();


                while (!inFile.EndOfStream)
                {
                    


                    //input file
                    string[] fields = inFile.ReadLine().Trim().Split(' ');
                    annualInterestRate = Double.Parse(fields[0]);
                    savingsBalance = Double.Parse(fields[1]);
                    accountNumber = fields[2];
                    accountHolder = fields[3];
                    


                    //set info from input file
                    account1.setAccountNumber(accountNumber);
                    account1.setAccountHolder(accountHolder);
                    account1.ModifyInterestRate(annualInterestRate);
                    account1.ModifySavingsBalance(savingsBalance);


                    array[i] = new SavingsAccount(annualInterestRate, savingsBalance, accountNumber, accountHolder);
                    i++;
                        
                  
                }
            }

           

    The input file is still the same.

    Tuesday, February 14, 2012 9:15 PM
  • What locale are you in? Some locales use a comma instead of a decimal point. If you are in such a locale, then by default Double.Parse() will be expecting a comma instead of a decimal point.

    What happens if you change the Double.Parse() to:

    Double.Parse(fields[x], System.Globalization.CultureInfo.InvariantCulture);

    Tuesday, February 14, 2012 9:21 PM
  • I'm in the US. So it would the be the decimal not the comma.
    Tuesday, February 14, 2012 9:34 PM
  • In that case, print out the fields that you're parsing to be absolutely sure what the strings are. (Or just inspect fields[] in the debugger.)

    Tuesday, February 14, 2012 9:46 PM
  • I don't know much about fields, when i check fields in the debugger all i see is:

    Name:              Value:

    fields              {string [1]}

    [0]           ""

    Would it be easier if i just sent your the project file with the input file and you checked it out yourself?

    Tuesday, February 14, 2012 10:10 PM
  • I don't really have time for that I'm afraid.

    I think that you don't have the data that you think you do - maybe add a check of the length of the string you read in before you try to parse it?

    Tuesday, February 14, 2012 10:15 PM
  • Well this is strange. I went through and checked the array and everything filled out perfectly. Array indexes 0 through 3 filled with all the info from the input file and the rest of the array stayed with the default values that it had. So technically, it looks like everything worked, just for some reason, its bringing up this eror. Could it be that the program is looping again even though there are no more values in the input file?
    Wednesday, February 15, 2012 12:05 AM
  • Hello there,

    I have re-written a sample based on your code, and everything seemed to work perfectly well.

    The only change in the code I have made was to comment the following lines as I donot know what code you have written in these methods.

                    //set info from input file
                    account1.setAccountNumber(accountNumber);
                    account1.setAccountHolder(accountHolder);
                    account1.ModifyInterestRate(annualInterestRate);
                    account1.ModifySavingsBalance(savingsBalance);

    So, it's my strong assumption that you are missing something in these methods.Please make sure if All is well in these methods,else post them here so that we can help you..!!!


    Thanks, Satish Bommideni Success usually comes to those who are too busy to be looking for it.

    Wednesday, February 15, 2012 4:50 AM
  • Well this is strange. I went through and checked the array and everything filled out perfectly. Array indexes 0 through 3 filled with all the info from the input file and the rest of the array stayed with the default values that it had. So technically, it looks like everything worked, just for some reason, its bringing up this eror. Could it be that the program is looping again even though there are no more values in the input file?
    Perhaps there's a blank line at the end of the input file or something?
    Wednesday, February 15, 2012 8:26 AM
  • Hi jsanch16,

    Welcome to the MSDN forum!

    How is it going with the problem?

    I agree with Matthew' opinion on that there might be some "blank" value for the fields, according to the debug result you have showed for us. 

    Name:              Value:

    fields              {string [1]}

    [0]           "" 

    Perhaps you need to check the content of your text file first and try the following code:

            static void teststring()
            {
                StreamReader infile = new StreamReader(@"E:\test.txt");  
                 while (!infile.EndOfStream)
                {
                     string[] fields = infile.ReadLine().Trim().Split(' ');
                     foreach(string s in fields)
                     {
                         if (s !=string.Empty) // Check first!
                         {
                             Console.WriteLine(s);
                         }
                     }
                 }
            }

    Below is the original text file:

    If don't check the string first, I get the following result:

    Hope it helps.

    Thanks.


    Yoyo Jiang[MSFT]
    MSDN Community Support | Feedback to us

    Thursday, February 16, 2012 8:29 AM
  • I think you're finding something inevitable -- when processing raw I/O like this you should really always  have some sort of validation.  A couple of points to start with:

    1. You may want to add the StringSplitOptions.RemoveEmptyEntries argument when you split the string, that way multiple spaces between values will get collapsed.
    2. Validate each array of pieces (the array I called "fields") for length
    3. To be really robust, use the double.TryParse method to check whether the first two chunks are really numbers.

    Also, you've got some other issues in your program:

    • You create an account1 object and change the values on every single iteration, but then never actually use it.
    • You fill your array with new Acounts but then overwrite them with other new accounts in the loop. Unless this stuff is in there purely for testing purposes, remove it.
    • You never do any array resizing or bounds checking, so it's quite likely that the array you have provided is not the correct length. You should address this.
    • You never closed your stream! I'll recommend you use a using block, especially since errors may occur while the stream is open

    Maybe this can get you started on the right track of proper data validation, and the other points:

        public static void LoadArray(SavingsAccount[] array) {
            string accountHolder = " ";
            string accountNumber = " ";
            double annualInterestRate = 0.0;
            double savingsBalance = 0.0;
            Array.Resize(ref array, 0); // Erase elements of existing array
    
            using (StreamReader inFile = new StreamReader(@"C:\Users\Juan D Sanchez\Desktop\accountdata.txt")) {
                int i = 0;
                while (!inFile.EndOfStream) {
                    string[] fields = inFile.ReadLine().Trim()
                                        .Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
    
                    if (fields.Length == 0) {
                        //Emtpy line. Skip it and continue.
                    }
                    else if (fields.Length == 4) {
                        if (!double.TryParse(fields[0], out annualInterestRate)) {
                            throw new ArgumentException("Cannot parse value '" + fields[0] + "' as a double");
                        }
                        if (!double.TryParse(fields[1], out savingsBalance)) {
                            throw new ArgumentException("Cannot parse value '" + fields[1] + "' as a double");
                        }
                        accountNumber = fields[2];
                        accountHolder = fields[3];
    
                        Array.Resize(ref array, i + 1);
                        array[i] = new SavingsAccount(annualInterestRate, savingsBalance, accountNumber, accountHolder);
                        i++;
                    }
                    else {
                        throw new IndexOutOfRangeException("Input string does not have the right number of fields!");
                    }
                }
                inFile.Close();
            }
        }


    jmh

    Thursday, February 16, 2012 3:40 PM
  • Hi jsanch,

    Welcome to the MSDN forum!

    I temporarily mark the replies as answers, and you can unmark them if they provide no help.

    If you have any concern, please let us know.

    Thanks for your understanding and have a nice day!

    yoyo


    Yoyo Jiang[MSFT]
    MSDN Community Support | Feedback to us

    Monday, February 27, 2012 9:17 AM