Перейти к содержимому

Readkey c что это

  • автор:

Difference between Console.Read() and Console.ReadLine()?

I’m new to this field and I’m very confused: what is the real difference between Console.Read() and Console.ReadLine() ?

12 Answers 12

Console.Read() reads only the next character from standard input, and Console.ReadLine() reads the next line of characters from the standard input stream.

Standard input in case of Console Application is input from the user typed words in console UI of your application. Try to create it by Visual studio, and see by yourself.

Magellan's user avatar

VMAtm's user avatar

These are the methods of system.console

    (returns a character): reads only one single character from the standard input stream or command line. Usually used when you’re giving options to the user in the console to select from, such as select A, B or C. Another prominent example, Press Y or n to continue. (returns a string): or Console.Readline() reads a single line from the standard input stream or the command line. As an example, it can be used to ask the user enter their name or age. It reads all the character till we press enter. (returns an int): or Console.Read() reads only one single character from the standard input stream. Similar to ReadKey except that it returns an integer. It returns the next character from the input stream, or returns (-1) if there is no more character to be read.

(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.ReadKey() Method in C#

Console.ReadKey() Method makes the program wait for a key press and it prevents the screen until a key is pressed. In short, it obtains the next character or any key pressed by the user. The pressed key is displayed in the console window(if any input process will happen). There are two methods in the overload list of this method as follows:

ReadKey() Method

This method is used to get the next character or function key pressed by the user. The pressed key is displayed in the console window.

Syntax: public static ConsoleKeyInfo ReadKey ();

Return Value: This method returns an object that describes the ConsoleKey constant and Unicode character(if any), it corresponds to the pressed key.

Exception: This method will give InvalidOperationException if the In property is belongs to some stream which is other than the console. “In” property is use to take standard input stream.

Below programs illustrate the use of the above-discussed method:

Example 1:

Output:

Example 2:

Output:

Example 3:

Output:

ReadKey(Boolean) Method

This method is more similar to the previous method, that is, it also obtains the next character or any key pressed by the user. The only difference is that the pressed key is optionally displayed in the console window.

Syntax: public static ConsoleKeyInfo ReadKey (bool key);
Here, “key” is used to determines whether to display the pressed key in the console window. If “true” then the pressed key will not be shown in the output window. If “false” then the pressed key will be shown in the output window.

Return Value: This method returns an object that describes the ConsoleKey constant and Unicode character(if any), it correspond to the pressed key.

Exception: This method will give InvalidOperationException when the In property is belongs to some stream which is other than the console. “In” property is use to take standard input stream.

C# Console.ReadKey Method

Console.ReadKey helps create interactive console programs.

It does not require the user to press enter before returning. It can read modifiers such as control. It enables more powerful text programs.

Example. In this program, we use the Console.ReadKey public static method with no arguments. The return value of the Console.ReadKey method is an instance of the ConsoleKeyInfo struct. You can declare a local variable of this type.

And: After ReadKey returns, the struct is assigned. You can call instance properties on the struct instance to determine the input.

When you hover your mouse over the local variable of type ConsoleKeyInfo, Visual Studio tells you the type is struct. This means it is a value type and that it is basically immutable. But the local variable can be reassigned.

Note: The ReadKey method will return a new ConsoleKeyInfo instance each time it is called.

The ReadKey method immediately causes the program execution to stop and wait for the input. However, unlike other Console methods, ReadKey will immediately return when a key has been pressed by the user.

Tip: Modifier keys will not cause the immediate return, so control sequences are possible.

Using Key property on ConsoleKeyInfo. When you call the Key property accessor on the local ConsoleKeyInfo variable, you are reading the values that were already set in the struct.

Here: The escape key is detected. The enter key does not need to be pressed to cause the program code to resume execution.

The Modifiers property returns a value of type ConsoleModifiers, which is an enumerated constant. You can call the Modifiers property and immediately test it against the ConsoleModifiers constants, such as ConsoleModifiers.Control.

Interaction. We next emphasize one of the uses for the ReadKey method. With this method, you can create fully interactive console programs in the C# language. This allows you to implement simple games, such as maze programs and adventure games.

You could use a maze program with a pathfinding algorithm to learn more about graph algorithms and other searching routines. In the old days of computing, many adventure games were implemented in console form.

Работа с консолью в C# (класс Console)

Несмотря на развитие приложений с графическим интерфейсом пользователя (GUI), работа в консоли всё равно занимает отнюдь не последнее место при разработке программ и не только в C#. В ряде случаев, работа с консолью просто необходима, например, при разработке приложений для работы с сетью. Более того, когда необходимо написать небольшой тестовый пример или программу для вычислений чего-либо, то намного проще сосредоточиться именно на основной функции программы — расчётах, чем тратить лишнее время на разработку графического интерфейса приложения.

Класс Console

Класс Console в Windows предоставляет нам стандартные потоки ввода/вывода или, если говорить очень просто — окно со специальными свойствами. У этого класса есть набор специальных свойств, которые позволяют управлять этими потоками ввода/вывода, а также украшать, при необходимости, внешний вид консольного приложения, например, менять цвет фона, текста и т.д.

Консольный вывод (методы WriteLine, Write)

Для того, чтобы вывести какое-либо значение в консоль, у класса Console объявлены методы Write и WriteLine , которые имеют различные версии, позволяющие без лишних преобразований выводить в консоль строки, числа, значения типа bool и т.д. Ключевое отличие Write от WriteLine заключается в том, что WriteLine записывает строку в консоль и устанавливает признак окончания строки, т.е. следующий за вызовом WriteLine вывод в консоль будет происходить со следующей строки. Вызов Write оставляет курсор на той же строке. Например,

Выведет в консоль текст в одну строку:

Следующий пример выведет в консоль несколько строк:

Обратите внимание, что мы смогли вывести различные типы данных в консоль — строку, целое число, значение bool и число с плавающей запятой.

Вывод нескольких значений

Нередко бывает необходимо вывести в консоль сразу несколько значений. В этом случае, мы можем воспользоваться двумя подходами. Первый — достаточно старый метод с использованием аргументов. Например:

здесь значения переменных вставляются в строку в соответствии с указанными в фигурных скобках порядковыми номерами (номера начинаются с нуля). В консоли мы увидим следующий вывод:

то есть, порядковому номеру 0 соответствует значение переменной name , 1 — age , 2 — height .

Второй метод — использование интерполяции строк. Это более новый подход и, на мой взгляд, более интуитивно понятный. Например, выведем те же самые переменные, что и в предыдущем примере, используя интерполяцию:

Во-первых, перед строкой указан символ $ , что говорит нам о том, что строка интерполируется. Во-вторых, в фигурных скобках мы уже указываем не номера аргументов метода WriteLine , а непосредственно сами переменные. Результат вывода в консоль будет точно такой же, но строка стала более понятной и читаемой. Возможности интерполяции строк более широкие, чем в представленном примере и об этой замечательной возможности мы ещё поговорим, когда будем рассматривать вопросы связанные с работой со строками.

Консольный ввод (методы Read, ReadLine и ReadKey)

Раз можно вывести значение в консоль, то можно значение и прочитать из консоли и присвоить его какой-либо переменной. Для чтения значений из консоли используются три метода — Read , ReadLine и ReadKey .

Чтение следующей строки (ReadLine)

Отметим, что ReadLine считывает именно строку, то есть, успешным результатом выполнения метода будет string . Если же ReadLine не может считать строку, то возвращается значение null . В примере выше мы обозначили тип переменной name как string? , что дословно означает следующее: переменная должна содержать значение типа string , но также может содержать и null . На возможность переменной хранить null указывает знак вопроса после типа.

Чтение следующего символа (Read)

Этот метод применяется сравнительно реже, чем предыдущий, но, тем не менее, также может нам пригодиться. Метод Read считывает следующий символ из строки и возвращает его значение в виде значения int32 . Если чтение символа не удалось, что метод возвращает значение -1 .

Чтение следующего нажатого символа или функциональной клавиши (ReadKey)

В отличие от методов Read и ReadLine метод ReadKey возвращает специальную структуру ConsoleKeyInfo , содержащую информацию о нажатой клавише. Например, с помощью ReadKey можно отслеживать какие функциональные клавиши пользователь нажимает

здесь мы используем цикл do. while и считываем очередную нажатую пользователем клавишу до тех пор, кока не будет нажата клавиша Enter . При этом, если пользователь нажмет клавиши F1 или Backspace , то программа выдаст предупреждение.

Также метод ReadKey удобно вставлять в самом конце консольной программы для того, чтобы окно консоли не закрывалось автоматически после окончания работы программы.

Итого

Сегодня мы рассмотрели основные методы для работы с консолью в C# — ввод и вывод данных с использованием различных методов. Для вывода данных в консоль используются методы Write и WriteLine , в для ввода — Read , ReadLine и ReadKey . На этом работа с консолью не заканчивается и в следующих частях мы рассмотрим то, как сделать консольный вывод в ваших приложениях бол

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

Школа онлайн с государственным аттестатом