Difference between Console.Read(); and Console.Readline();

Asked

Viewed 11,142 times

10

I’m starting to learn C# and I got a little confused by one thing.

What’s the real difference between Console.Read(); and Console.ReadLine(); ?

  • http://stackoverflow.com/questions/6825943/difference-between-console-read-and-console-readline

  • 2

    View documentation: Console.Read and Console.ReadLine

  • @dcastro Thanks for the references, but the reply of the bigown explains more clearly than the documentation.

3 answers

11


The first reads one character of buffer and the second reads a line, that is, all characters until it finds an end of line indicator.

For reading only one character Read() returns an integer indicating what would be the character read. It is not even a char. A conversion is required if you need the information as a character. And obviously if you need how string conversion is also required. The ReadLine() returns a string to accommodate the entire line. The end-of-line sign is not part of this string resultant.

This buffer Usually it’s the keyboard. There are no guarantees coming from there but the default input used by the console is this device. Obviously it may have been redirected but C# or . NET does not need to know this. Therefore, normally the end-of-line indicator is generated when the ENTER is triggered. Technically speaking is when you receive a string NewLine.

Source code of Read() (.NET Core) and of ReadLine() (.NET Core). You need to dig into other parts of the code to understand everything, but it’s a start.

  • So if I try to read something with read in a variable of type string will generate an error?

  • Yes, I edited to report this.

  • Thanks, I get it now.

1

Basically, you will want to use the Console.Read() when you want the return ASCII VALUE of the first character typed.

If you want only one character you will have to do some checking, because no value will return like this.

Then:

  • Console.Readkey.() Returns the value of the pressed key
  • Console.Readline() Returns the value of the entire line
  • Console.Read() Returns the ASCII value of the first character typed in the line

0

I just understood this in practice where a variable of my code (int) would receive via keyboard, for example: 240 and later made a multiplication of this variable with another, but the final result of multiplication always went wrong. Testing the output of the variable it displayed 50 instead of 240.

Read()fault; Solution given by a friend here from the stack

variável = Convert.Toint32(Console.Readline());

  • In general this is not appropriate.

  • @Maniero , pq? Could I talk more about?

  • I have already answered several times about this: https://answall.com/search?q=user%3A101+tryparse

Browser other questions tagged

You are not signed in. Login or sign up in order to post.