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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With