Console input/output in C#
When a console application starts, the operating system automatically associates three I/O streams with the console: standard input stream, standard output stream, and standard error output stream. To read a line of text from the console window, we use the Console.ReadLine() method. This will read
an input stream (terminated when the user presses the Return key) from the console window and return the input string. There are also two corresponding methods for writing to the console, which you have already used extensively:
➤ Console.Write() — Writes the specified value to the console window.
➤ Console.WriteLine() — This does the same, but adds a newline character at the end of the output.
Various forms (overloads) of these methods exist for all the predefined types (including object), so in most cases you don’t have to convert values to strings before we display them. For example, the following code lets the user input a line of text and displays that text:
string s = Console.ReadLine();
Console.WriteLine(s);
Console.WriteLine() also allows you to display formatted output in a way comparable to C’s printf() function. To use WriteLine() in this way, you pass in a number of parameters. The first is a string containing markers in curly braces where the subsequent parameters will be inserted into the text. Each marker contains a zero-based index for the number of the parameter in the following list. For example, {0} represents the first parameter in the list. Consider the following code:
int i = 10;
int j = 20;
Console.WriteLine("{0} plus {1} equals {2}", i, j, i + j);
Дата добавления: 2015-09-18 | Просмотры: 532 | Нарушение авторских прав
1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 |
|