-1

I'm just beginning to learn C#, I'm trying to understand the working of Console.ReadLine() Console.Read(), while trying to understand how Console.Read() works Im encountering the following issue. I tried executing the following program.`

enter cusing System;

namespace Variables
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Give me an input :");
            Console.Read();
            Console.Write("Give me an input :");
            Console.Read();

        }
    }

In the console I'm able to give an input for the first Console.Read() statement, but where as for the later statement the program finishes its execution without even accepting the input. Please explain why the program terminates without accepting any input.

enter image description here

squillman
  • 13,363
  • 3
  • 41
  • 60
  • 5
    `Constole.Read()` only reads a single character. Is it possible that you are typing more than a single character for the first statement? If so then I expect a subsequent character is getting read by the second statement and your program then exits. – squillman May 19 '21 at 12:26
  • From your screenshot I'm guessing that you are typing 1 and then pressing Enter. That Enter keystroke (that is, newline character) will be the input to your second `Console.Read()` – squillman May 19 '21 at 12:28
  • Check [msdn](https://learn.microsoft.com/en-us/dotnet/api/system.console.readkey) when you suspect something is not working as you think it should. – Sinatr May 19 '21 at 12:32
  • Does this answer your question? [Difference between Console.Read() and Console.ReadLine()?](https://stackoverflow.com/questions/6825943/difference-between-console-read-and-console-readline) –  May 19 '21 at 12:32
  • Thanks a lot @squillman, i was doing the same thing as you mentioned, now got it figured out. – sai harsha May 22 '21 at 09:04
  • Thanks @Sinatr, will be helpful in the future. – sai harsha May 22 '21 at 09:04

1 Answers1

1

Each call to Console.Read() returns 1 character at a time, but the input is buffered until you first terminate the line (i.e. when you press Enter).

e.g. If you type 1[Enter], the first Console.Read() will return 1 and the second call will return [Enter]. The first call to Read() will block, whereas the second will not block ([Enter] will be returned immediately).

Any subsequent call to Read() will block again as the input buffer is now empty.

BlokeTech
  • 317
  • 1
  • 7