Search code examples
c#user-inputexplicitsharpdevelopformatexception

"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:

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().