What is the difference between reading and reading in C #?

What is the difference between read() and readline() in C #?

Maybe we don’t use it, but in my academy the only difference is that it has a "string" and the other does not ... In C ++ there is a "cin" and it has an "endl" to add strings. Can someone tell me the difference?

+4
source share
2 answers

Do you mean TextReader.Read and TextReader.ReadLine ?

One overload of TextReader.Read reads characters into the buffer (a char[] ), and you can specify how many characters you want to read (at most). Another reads one character, returning int , which will be -1 if you reach the end of the reader.

TextReader.ReadLine reads the whole line as a string , which does not include the line terminator.

As far as I know, endl more often used in combination with cout in C ++:

 cout << "Here a line" << endl; 

In .NET you should use

 writer.WriteLine("Here a line") 

do the same thing (for the corresponding TextWriter , or use Console.WriteLine for the console).

EDIT: Console.ReadLine reads a line of text, while Console.Read reads a single character (it is like a seamless TextWriter.Read overload).

Console.ReadLine() is basically the same as Console.In.ReadLine() , and Console.Read() is basically the same as Console.In.Read() .

EDIT: in response to your comment on another answer you cannot:

 int x = Console.ReadLine(); 

because the return type Console.ReadLine() is a string, and there is no conversion from string to int . You can do

 int x = Console.Read(); 

because Console.Read() returns an int . (Again, this is a Unicode code point, or -1 for "end of data.")

EDIT: if you want to read an integer from the keyboard, that is, the user enters "15" and you want to get it as an integer, you should use something like:

 string line = Console.ReadLine(); int value; if (int.TryParse(line, out value)) { Console.WriteLine("Successfully parsed value: {0}", value); } else { Console.WriteLine("Invalid number - try again!"); } 
+8
source

If you are talking about Console.Read and Console.ReadLine, the difference is that Read only returns only one character, and ReadLine returns the entire input line. It is important to note that in both cases the API call will not be returned until the user presses ENTER to send the text to the program. Therefore, if you type "abc" but do not press ENTER, both Read and ReadLine will lock until you do.

+2
source

All Articles