(2) console I/O
The console I/O is implemented through standard data stream console. In, console. Out, and console. Error.
Console. In is an instance of the textreader class. You can use methods defined by the textreader class. However, in general, we use the methods provided by the console class. There are three methods: Read (), Readline (), and readkey () functions.
The read () function is usually used to read a single character. It is a static function used to read the next character from the console and return the int type value of the read character. If you need to use this character, the Char keyword must be used for forced type conversion. This method returns-1 when the call fails and throws an ioexception.
By default, the console inputs are row-by-row buffered, so you must press enter to send the entered charactersProgram. When you press enter, the system puts a line feed sequence containing the Enter key into the input data stream, and the characters are stored in the input buffer until they are read.
If you want to read a string, you need to use the Readline () function. This function keeps reading characters and returns these characters as a string object when you press Enter.
After. NET Framework 2.0, a new method readkey () is added to the console class. This function reads keys in a non-row-by-row buffer mode.
The readkey () method has two forms:
Static consolekeyinfo readkey ();
Static consolekeyinfo readkey (bool intercept );
The first form waits for the input from the keyboard. When you press a key, the key is immediately returned and the corresponding key is displayed on the screen. The second form also waits for input from the keyboard. This key is returned immediately when a key is pressed. If intercept is true, this key is not displayed. If intercept is a key, the corresponding key is displayed on the screen.
From the above function definition, we can see that this function returns a lelekeyinfo object, which is a struct and contains the following read-only attributes:
Char keychar
Consolekey key
Lelemodifiers Modifiers
The keychar attribute contains the char type value that matches the pressed key. The key attribute contains an enumeration value defined by the consolekey enumeration. The consolekey enumeration defines the key value corresponding to all the buttons on the keyboard.
The lelemodifiers enumeration defines modifiers for keyboard keys, such as shift, Ctrl, and ATL.
Console. out and console. errors are textwriter-type objects. Although the methods defined by the console class can be called for output, the console class can directly call the output functions write and writeline functions.
By default, console. error is output to the console, but we can redirect to a disk file instead of a screen to output the error information to the log file without affecting the console output.