Метод Console.ReadLine () в C #
Этот метод используется для чтения следующей строки символов из стандартного входного потока. Он входит в класс Console (пространство имен системы). Если стандартным устройством ввода является клавиатура, метод ReadLine блокируется, пока пользователь не нажмет клавишу Enter. И если стандартный ввод перенаправляется в файл, то этот метод считывает строку текста из файла.
Syntax: public static string ReadLine ();
Return Value: It returns the next line of characters of string type from the input stream, or null if no more lines are available.
Исключения:
- IOException : если произошла ошибка ввода-вывода.
- OutOfMemoryException : если недостаточно памяти для выделения буфера для возвращаемой строки.
- ArgumentOutOfRangeException : если количество символов в следующей строке символов больше, чем MaxValue.
Программа ниже иллюстрирует использование вышеупомянутого метода:
Example 1: Here, take input from the user. Since age is an integer, we typecasted it using Convert.ToInt32() Method. It reads the next line from the input stream. It blocks until Enter key is pressed. Hence it is commonly used to pause the console so that the user can check the output.
// C# program to illustrate // the use of Console.ReadLine() using System; using System.IO; class GFG { // Main Method public static void Main() { int age; string name; Console.WriteLine( "Enter your name: " ); // using the method // typecasting not needed // as ReadLine returns string name = Console.ReadLine(); Console.WriteLine( "Enter your age: " ); // Converted string to int age = Convert.ToInt32(Console.ReadLine()); if (age >= 18) { Console.WriteLine( "Hello " + name + "!" + " You can vote" ); } else { Console.WriteLine( "Hello " + name + "!" + " Sorry you can"t vote" ); } } } |
Выход:
Example 2: To pause the console
// C# program to illustrate // the use of Console.ReadLine() // to pause the console using System; using System.IO; class Geeks { // Main Method public static void Main() { string name; int n; Console.WriteLine( "Enter your name: " ); // typecasting not needed as // ReadLine returns string name = Console.ReadLine(); Console.WriteLine( "Hello " + name + " Welcome to GeeksforGeeks!" ); // Pauses the console until // the user preses enter key Console.ReadLine(); } } |
Выход:
Объяснение: В выходных данных выше видно, что консоль приостановлена. Курсор будет непрерывно мигать, пока вы не нажмете клавишу Enter.
Ссылка:
- https://docs.microsoft.com/en-us/dotnet/api/system.console.readline?view=netframework-4.7.2