-2

I'm trying to use C#'s Console.ReadLine() method to take user input from the console, then subsequently print text on the same line.

Code being used:

using System;

namespace Test {
    class Program {
        static void Main(string[] args) {
            Console.ReadLine();
            Console.Write(" out");
        }
    }
}

What I'm expecting from the console:

in out

What's actually being produced:

in
 out

Note that in here is being typed into the console.

Any assistance would be greatly appreciated. Thanks!

-chris

  • Are you _sure_ you want to use `Console.Read()`, not `Console.ReadLine()`? https://learn.microsoft.com/en-us/dotnet/api/system.console.read?view=net-7.0 – gunr2171 Nov 28 '22 at 00:47
  • Does this answer your question? [Difference between Console.Read() and Console.ReadLine()?](https://stackoverflow.com/questions/6825943/difference-between-console-read-and-console-readline) – Jim G. Nov 28 '22 at 00:52
  • @JimG. Yes, and no. I do realize now that I should be using `Console.ReadLine()`, but using that method instead of `Console.Read()` yields the same results. I've edited the post to reflect this. – chris.thorpe Nov 28 '22 at 00:57
  • You will need to use an input method that doesn’t echo what the user types. – 500 - Internal Server Error Nov 28 '22 at 01:10

1 Answers1

2

The problem is that it automatically echoes the user input, including the newline when the enter key is pressed. So you have to stop it from echoing the input and handle that yourself.

You can do this by using Console.ReadKey(Boolean) and passing true to intercept the key, and only write it to the output if it's not the enter key.

That would look like this:

using System;

namespace Test {
    class Program {
        static void Main(string[] args) {
            while (true) {
                var key = Console.ReadKey(true);
                if (key.Key == ConsoleKey.Enter) {
                    break;
                } else {
                    Console.Write(key.KeyChar);
                }
            }
            Console.WriteLine(" out");
        }
    }
}
Gabriel Luci
  • 38,328
  • 4
  • 55
  • 84