-5

I wrote a very basic program in C#. However, I don't understand the behavior of the executed program. Why does Read() interfere with ReadLine()?

int str = Console.Read();
string str1 = Console.ReadLine();

Console.WriteLine(str);
Console.WriteLine(str1);
abdeaitali
  • 155
  • 1
  • 2
  • 7
  • 2
    @TomTom you guys could at least answer him in the comments instead of just telling him to leave. He is obviously a beginner and doesn't know how to help himself yet... we were all there at one point. pescolino is right, so that's why I'm not answering OP here in the comments myself. – Millie Smith Sep 27 '14 at 19:00
  • 5
    I didn't vote, but just to help you understand why you might have gotten downvotes: It would be useful if you explain what input you tried, what result you got, and what result you expected. It will be difficult for people to help you if you say that you don't understand the behavior of the code, but don't specify what behavior you expect. – Reto Koradi Sep 28 '14 at 00:51
  • 1
    [Meta discussion about this question](http://meta.stackoverflow.com/q/272328/2982225) – Infinite Recursion Sep 28 '14 at 05:19
  • Thanks guys, this is by the way the first question I ask here. I appreciate your help. – abdeaitali Sep 29 '14 at 16:47

1 Answers1

1

The first method you are calling is Read which returns one character. But it blocks until you hit the Enter key.

From MSDN:

The Read method blocks its return while you type input characters; it terminates when you press the Enter key.

Then you call ReadLine which returns a line.

When you hit the Enter key the Read method will return the first character and remove it from the input stream. The following call to ReadLine will then immediately return the rest of the line.

Please note that if you enter a number Read will not return the number but the ASCII representation of the digit (49 for '1' etc.). If you are interested in getting an integer you should use ReadLine and use int.TryParse on the return value.

If you are interested in a single key you should prefer ReadKey as it only blocks for a single key.

pescolino
  • 3,086
  • 2
  • 14
  • 24
  • 1
    @Will: I had to rollback your edit because it was wrong. What you were describing is `ReadKey`. From MSDN: "The Read method blocks its return while you type input characters; it terminates when you press the Enter key." I think this weird behaviour was the cause for the question. – pescolino Sep 30 '14 at 21:57
  • 1
    You're right. My bad. –  Oct 01 '14 at 12:58