Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Console.ReadLine() isn't working-- it isn't asking for user input, console just skips it

Tags:

c#

This is my code. Just writing a simple program to practice with strings and use of its methods. I cannot, for the life of me, get the console to read the "Console.ReadLine()" that I want to store in the variable "myNameFirst".

{
    class Program
    {
        static void Main(string[] args)
        {

            Console.WriteLine("Please enter a string here and press enter.");
            string user = Console.ReadLine();

            Console.WriteLine("Now enter a character to search for:");
            char userChar = (char)Console.Read();

            Console.WriteLine($"The index of the letter {userChar} is {user.IndexOf(userChar)}");


            Console.WriteLine("What is your first name?");
            string myNameFirst= Console.ReadLine();
            Console.WriteLine(myNameFirst);

        }
    }
}

I have restarted my computer, I have re-installed Visual Studio, I have checked to make sure there were no typos. I have also searched through other questions and none seem to know how to fix the console skipping over the lines.

like image 462
AnnetheCyberLady9 Avatar asked Dec 21 '25 09:12

AnnetheCyberLady9


1 Answers

When you use Console.Read(), you only read one character (say, a), but you actually put in a and "new line" (\n). When your last Console.ReadLine() line is reached, it doesn't block because there is already a \n waiting in the buffer and so myNameFirst is empty.

To confirm it, change your last line to:

Console.WriteLine("My first name is: " + myNameFirst);
// Print out: My first name is: 

To solve the problem, clear the "new line" with an extra Console.ReadLine():

char userChar = (char)Console.Read();
Console.ReadLine(); // Add this
like image 179
Luke Vo Avatar answered Dec 23 '25 23:12

Luke Vo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!