Home > Mobile >  Print text on same line as user input using C# Console
Print text on same line as user input using C# Console

Time:11-28

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

CodePudding user response:

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");
        }
    }
}
  • Related