Search code examples
c#console.readline

Does Console.Read() takes the first digit as input when a two/more digit number as entered?


I am new to C#. So, I was practicing by writing some simple codes. I decided to write a code where the user will enter a number and the same number will be shown as the output. I wrote the following code and it worked perfectly.

However,when I decided to replace Console.Readline() by Console.Read() to see what would be the output, and ran the code, I found the output to be the ASCII Code of the first digit of the number that I entered. [That is when I entered 46, the output was 52.]

Whereas, when I had used Console.ReadLine(), the entire two digit number was shown.

According to me, Shouldn't it be that Console.Read() displays only the first digit of the number entered while Console.ReadLine() shows the entire number?

using System;

namespace ConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            int num1;
            Console.Write("Enter a number:");
            num1 = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine("The number is: " + num1);
            Console.ReadKey();

        }
    }
}

Solution

  • From the documentation, Console.Read returns:

    The next character from the input stream, or negative one (-1) if there are currently no more characters to be read.

    as an int.

    The int is the ASCII value of the character read. You just have to cast to char to get the character:

    int characterRead = Console.Read();
    if (characterRead != -1) {
        char c = (char)characterRead;
    
        // if you want the digit as an int, you need
        int digit = Convert.ToInt32(c.ToString());
    }
    

    Also, note that a second call to Console.Read will read the second digit. If you want to skip this, you need a call to Console.ReadLine to clear anything that's unread.