0

I'm a beginner in C# so please be patient with me. :) I'm practicing to write a simple C# code to understand how this language works. I have tried to read characters, integers and strings from console but between different tries/methods the buffer never empties. I would like to clear the buffer of console between each methods, for example:

using System;

namespace ElsoKonzolAppom
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Write something!");
            string text1 = Console.ReadLine();
            Console.WriteLine("Your text:" + text1);

            //here, I would like to clear the buffer

            int number1 = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine("Your first number:" + number1);

            //here, I would like to clear the buffer

            int number2 = Console.Read();
            Console.WriteLine("Your second number:" + number2);

        }
    }
}

Probably this is something very trivial that I haven’t mastered yet.

James Z
  • 12,209
  • 10
  • 24
  • 44
Thend
  • 95
  • 7
  • 3
    Does this answer your question? [Clear Console Buffer](https://stackoverflow.com/questions/3769770/clear-console-buffer) – MDT Sep 30 '21 at 08:46
  • Dear Manti_Core, Unfortunately that question doesn't answer my problem. Also, that approach has been mentioned here below, and I have tried it, and did not solve my issue. (How can I remove the [duplicate] from the title?) Best, thend – Thend Sep 30 '21 at 09:22
  • you are chasing after the wrong thing to solve your current issue, in your code `int number2 = Console.Read()` you are just reading from same line of input stream, what you should be doing is Console.ReadLine() and convert it to int just like you are doing for the first integer – MDT Sep 30 '21 at 09:54
  • Hi Manti_Core, your recent answer was extremely helpful!!! I could manage to do it, thank you so much! I have changed the line from 'int number2 = Console.Read();' to 'int number2 = int.Parse(Console.ReadLine());' to read from a new line, as you mentioned. Thank you so much. (How can I up vote your comment?) – Thend Sep 30 '21 at 10:10

2 Answers2

1

As far i understood you want to clear input buffer? There is no method in console class for it. Try this:

while(Console.KeyAvailable) 
    Console.ReadKey(false); // skips previous inputs

Console.ReadKey(); // reads a new char

Use Console.ReadKey(true) if you don't want to print skipped chars.

If you want to clear the screen use:

Console.Clear()

Regards

Martin.Martinsson
  • 1,894
  • 21
  • 25
  • Hi Martin, I have tried both, but somehow I cannot get back the second number. This is what I get: Write something! asdf Your text:asdf 5 Your first number:5 6 Your second number:54 – Thend Sep 30 '21 at 09:07
0

you can use Console.ReadKey(false); // true = hide input

Amara Miloudi
  • 122
  • 1
  • 6