Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

visual-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 one has "line" and the other don't have... In c++, there is "cin" and it has "endl" to add line. Can somebody tell me the difference?

like image 402
Sherif Avatar asked Dec 29 '22 22:12

Sherif


2 Answers

Do you mean TextReader.Read and TextReader.ReadLine?

One overload of TextReader.Read reads characters into a buffer (a char[]), and you can specify how many characters you want it to read (as a maximum). Another reads a single character, returning an int which will be -1 if you've reached the end of the reader.

TextReader.ReadLine reads a whole line as a string, which doesn't include the line terminator.

As far as I'm aware, endl is more commonly used in conjunction with cout in C++:

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

In .NET you'd use

writer.WriteLine("Here's a line")

to accomplish the same thing (for an appropriate TextWriter; alternatively use Console.WriteLine for the console).

EDIT: Console.ReadLine reads a line of text, whereas Console.Read reads a single character (it's like the parameterless overload of TextWriter.Read).

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

EDIT: In answer to your comment to the other answer, you can't do:

int x = Console.ReadLine();

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

int x = Console.Read();

because Console.Read() returns an int. (Again, it's the Unicode code point or -1 for "end of data".)

EDIT: If you want to read an integer from the keyboard, i.e. the user types in "15" and you want to retrieve that 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!");
}
like image 96
Jon Skeet Avatar answered Jan 14 '23 14:01

Jon Skeet


If you're talking about Console.Read and Console.ReadLine, the difference is that Read only returns a single character, while ReadLine returns the entire input line. Its important to note that in both cases, the API call won't return until the user presses ENTER to submit the text to the program. So if you type "abc" but don't press ENTER, both Read and ReadLine will block until you do.

like image 24
Bruce Avatar answered Jan 14 '23 14:01

Bruce