The following code asks for your name and surname.
class Program
{
static void Main(string[] args)
{
Console.Write("Enter your name: ");
string s = Console.ReadLine();
Console.WriteLine("Your name: " + s);
Console.Write("Enter your surname: ");
int r = Console.Read();
Console.WriteLine("Your surname: " + r);
Console.ReadLine();
}
}
After entering the name, the program successfully displays your input. However, after entering a surname, the program stops immediately. From my understanding, Console.Read() should return an int value of the first character of the string I enter (ASCII code?).
Why does the program terminate right after Console.Read()? Shouldn't Console.ReadLine() ensure the program stays open? I am using Visual Studio 2012.
When you tell the console to enter your surname you are asking for a single character.
Console.Write("Enter your surname: ");
int r = Console.Read();
This surely should be a ReadLine followed by another ReadLine before exit. You are probably entering the first character (into Read), followed by subsequent characters, then hitting enter to accept the surname but you are actually on the ReadLine that will exit. So:
class Program
{
static void Main(string[] args)
{
Console.Write("Enter your name: ");
string s = Console.ReadLine();
Console.WriteLine("Your name: " + s);
Console.Write("Enter your surname: ");
// change here
string surname = Console.ReadLine();
Console.WriteLine("Your surname: " + surname);
Console.ReadLine();
}
}
The program does not terminate after int r = Console.Read() for me.