Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading