Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

"System.FormatException: Input string was not in a correct format."

"System.FormatException: Input string was not in a correct format."

This keeps stopping my program and telling me that I have not converted the user input to an integer (because user input is initially a string type).

Here’s the code for my C# project:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

using System;
namespace Project1 {
    class Program {
        static void Main(string[] args) {
            Console.WriteLine("PREPARING GAME: HEADS AND TAILS");
            Console.WriteLine("PRESS ENTER TO CONTINUE");
            Console.Read();
            Console.WriteLine("PICK A NUMBER:");
            Console.WriteLine("1: HEADS");
            Console.WriteLine("2: TAILS");
            Console.WriteLine("----------------");
            int playerNum = Convert.ToInt32(Console.ReadLine()); //Where the trouble happens
        }
    }
}

I’m not exactly sure why it keeps reporting the same error if I thought I fixed it already with the Convert.ToInt32() method. I tried converting it to int16 instead of int32 since the whole numbers are small but it still throws the same exception error. I don’t think I would need a double either because I really am only asking for a small whole number.

>Solution :

Console.Read() reads one char off the input stream, a windows carriage-return is two characters \r\n so you are leaving \n in the buffer.

When you reach your Console.ReadLine() it’s reading the rest of the input buffer (\n) which is passed as a parameter to Convert.ToInt32("\n") and an exception is thrown.

Change the first Read() call to ReadLine() to read the full carriage-return from the buffer, then the buffer will be empty when you reach the next ReadLine().

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading