2

I want to keep reading lines of the user, but when this user presses on escape I want it to stop. But how can I keep reading single keys (for the escape), while meanwhile reading lines? I hope the question will be more clear after giving my code:

int number;
do
{
      string a = Console.ReadLine();
      try
      {
          Int32.TryParse(a, out number);
      }
      catch
      {
          Console.WriteLine("I only accept int");
      }
      finally
      {
          Console.Writeline(number);
      }
} while (Console.ReadKey(true).Key != ConsoleKey.Escape);
wouter
  • 359
  • 4
  • 15

2 Answers2

2

as you have written, you want to read lines until escape is pressed, but as your code says, you want to read only integers. Here's what I think is what you want,

        int number = 0;
        do
        {
            while (!Console.KeyAvailable)
            {
                string a = Console.ReadLine();
                bool bWriteNumber = false;
                try
                {
                    number = int.Parse(a);
                    bWriteNumber = true;
                }
                catch
                {
                    Console.WriteLine("Sorry! I only accept int");
                }
                finally
                {
                    if (bWriteNumber)
                        Console.WriteLine(number);
                }
            }
        } while (Console.ReadKey(true).Key != ConsoleKey.Escape);
Rohit Prakash
  • 1,975
  • 1
  • 14
  • 24
1

I am not sure to understand completely your question but you can test the code below if it matches your requirements

using System;
using System.Globalization;

namespace StackOverflow_31111668
{
    class Program
    {
        static void Main()
        {
            while (Console.ReadKey(true).Key != ConsoleKey.Escape)
            {
                var a = Console.ReadLine();
                int number;
                Console.WriteLine(!int.TryParse(a, out number) ? "I only accept int" : number.ToString(CultureInfo.InvariantCulture));
            }
        }
    }
}
labilbe
  • 3,501
  • 2
  • 29
  • 34