Console.ReadLine() does not end after I press enter

854 Views Asked by At

I am using VSCode to fiddle with C# and I have created a function that is supposed to print out a message (which it does) and then take an input and end the function (which it doesn't). I suspect that the issue is somewhere in Console.ReadLine(), and every guide I find shows Console.ReadLine() being used in exactly the same way, but nevertheless when I push enter while the program is running and after typing a valid String, the Console.ReadLine just repeats and I end up with a new line underneath the old one.

private static String Ask(String message){
    String messi = "";
    String ans = "";
    messi = message;
    Console.WriteLine(messi);
    Console.WriteLine("Arrived"); //This checks to make sure that we do reach ReadLine()
    //ans = Console.ReadLine();
    String s = Console.ReadLine();
    Console.WriteLine("ArrivedBefore");
    return ans;
}
3

There are 3 best solutions below

0
On

I solved this by writing my own ReadLine method

  private string ReadLine()
  {
      StringBuilder readString = new StringBuilder(50);
      while (true)
      {
          ConsoleKeyInfo keyInfo = Console.ReadKey();
          if (keyInfo.Key == ConsoleKey.Enter)
          {
              break;
          }
          else
          {
              readString.Append(keyInfo.KeyChar);
          }
      }

      return readString.ToString();
  }
1
On

Is the issue here that you are running the code via the "Debug Console" tab rather than from the "Terminal" tab.

I have had the same issue in Visual Studio Code

  • running my code in Visual Studio Code via the run command while the Debug Console is selected then "the Console.ReadLine just repeats and I end up with a new line underneath the old one."
  • running my code from a Command Window (having navigated to my project folder containing my csproj file) and executing a "dotnet run" command the code works as expected
  • running my code in Visual Studio Code via the run command while the Terminal tab is selected and my code runs as expected
0
On

Go to terminal where your cs file is located and run (In my case it is called Variable.cs):

dotnet run Variable.cs

and it worked for me.