Question Read() and ReadLine()

Lawrence

New member
Joined
Jul 11, 2016
Messages
2
Programming Experience
Beginner
Hi,
I am new to this forum and C#. I have following code.

C#:
[FONT=Consolas][SIZE=2][COLOR=#2b91af][FONT=Consolas][SIZE=2][COLOR=#2b91af][FONT=Consolas][SIZE=2][COLOR=#2b91af]Console.WriteLine("Enter a character");
[/COLOR][/SIZE][/FONT][/COLOR][/SIZE][/FONT][FONT=Consolas][SIZE=2][COLOR=#0000ff][FONT=Consolas][SIZE=2][COLOR=#0000ff][FONT=Consolas][SIZE=2][COLOR=#0000ff]int int1 = Console.Read();
Console.WriteLine(int1);
Console.WriteLine("Enter a string of characters");
string string1 = Console.ReadLine();
Console.WriteLine(string1);
Console.ReadLine();
[/COLOR][/SIZE][/FONT][/COLOR][/SIZE][/FONT][/COLOR][/SIZE][/FONT][/COLOR][/SIZE][/FONT]

When I executed this code,
1) Console window printed the following text: "Enter a character"
2) I entered 'a' and pressed Enter key
3) Console window displayed 97 and then printed the text: "Enter a string of characters"
4) I entered 'abcd' and pressed Enter key
5) I expected the text 'abcd" should be printed. However the console window vanished.

Any idea, why this happens?
 
The reason is that the Read method does not consume the line-termination character. When you hit 'a' and the press Enter, that Read call consumes the 'a' but not the Enter. That means that when you call ReadLine, which reads all the available text up to the next line break, is going to read no text up to that already present line break. Your last ReadLine is then going to read the line that you input last, i.e. "abcd" followed by a line break, and then the window closes.

As the documentation for the Read method states, you should be using the ReadLine or ReadKey method instead. ReadLine will read everything up to the line break, which you can then validate to ensure that it's just one character. ReadKey will read the input as soon as the press it and not wait for an Enter. I would suggest that your code should be like this:
Console.WriteLine("Enter a character");
int int1 = Convert.ToInt32(Console.ReadKey().KeyChar);
Console.WriteLine();
Console.WriteLine(int1);
Console.WriteLine("Enter a string of characters");
string string1 = Console.ReadLine();
Console.WriteLine(string1);
Console.ReadLine();
That will give you the output you expect if you do as you did before except without hitting Enter after the first 'a'.
 
Another option would be to stick with the Read call that you had but add a ReadLine call after it. That would consume the line break and it would also enable you to ignore anything the user entered after the first character.
C#:
Console.WriteLine("Enter a character");
int int1 = Console.Read();
[B][U][COLOR="#FF0000"]Console.ReadLine();[/COLOR][/U][/B]
Console.WriteLine(int1);
Console.WriteLine("Enter a string of characters");
string string1 = Console.ReadLine();
Console.WriteLine(string1);
Console.ReadLine();
 
Back
Top Bottom