I'm new to this field and I'm very confused: what is the real difference between Console.Read()
and Console.ReadLine()
?
This question is related to
c#
input
console
inputstream
MSDN is actually pretty clear on this one.
The difference of Read(),ReadLine() and Readkey() method are given below:
Read():This is static method in Console class:
int i = Console.Read();//it always return int value.
Console.WriteLine(i);
paste above code and give input '1', and the output will be 49. That is Console.Read give int value but that value will be the ASCII value of that.
ReadLine():
string s= Console.ReadLine();//it always return string value.
Console.WriteLine(s);
It gives the string as it is given in the input stream.
ReadKey(): this method is used to hold the output screen.when any key is press. Read() and ReadLine() is used the enter key for exit.
Console.Read()
reads just a single character, while Console.ReadLine()
reads all characters until the end of line.
Console.Read()
is used to read next charater from the standard input stream.
When we want to read only the single character then use Console.Read()
.
Console.ReadLine()
is used to read aline of characters from the standard input stream.
when we want to read a line of characters use Console.ReadLine()
.
The basic difference is:
int i = Console.Read();
Console.WriteLine(i);
paste above code and give input 'c', and the output will be 99. That is Console.Read give int value but that value will be the ASCII value of that..
On the other side..
string s = Console.ReadLine();
Console.WriteLine(s);
It gives the string as it is given in the input stream.
Difference between Read(),Readline() and ReadKey() in C#
Read()
-Accept the string value and return the string value.
Readline()
-Accept the string and return Integer
ReadKey()
-Accept the character and return Character
Summary:
1.The above mentioned three methods are mainly used in Console application and these are used for return the different values . 2.If we use Read line or Read() we need press Enter button to come back to code. 3.If we using Read key() we can press any key to come back code in application
Console.Read()
Console.ReadLine()
Console.ReadKey()
Console.Read()
=> reads only one character from the standard input
Console.ReadLine()
=> reads all characters in the line from the standard input
These are the methods of system.console
(There are more system.console methods like write() and writeline() as well which are used to write in command line, behaving similarly as read() and readline() methods)
This was clearly described with examples in the MSDN documentation (links are included above).
Console.Read()
basically reads a character so if you are on a console and you press a key then the console will close, meanwhile Console.Readline()
will read the whole string.
Console.Read()
reads a single key, where Console.Readline()
waits for the Enter key.
Source: Stackoverflow.com