Console INPUT/OUTPUT

Console input and output
Explains how user input and output is integrated in the C# program



CONSOLE INPUT

To read some text from the command line you use the Console.Read or Console.ReadLine method implemented in the .net framework. The difference between them is that the Console.Read method reads the next character from the command line, whereas Console.ReadLine reads the next line of characters instead of just a simple character. The Console.Read method returns an integer and should be cast to a char during the input. There is also a special function called Console.ReadKey( Boolean display) which obtains the key that is pressed on the keyboard and if the display parameter is false it depicts it.

CONSOLE OUTPUT

The functions used for this purpose is the Console.Write and Console.WriteLine(). They both write the specified value to the console window but the second also adds a new line character. The following snippet of code demonstrates the usage of input methods:
        static void Main()
        {
            char c;
            string myString;
            myString = Console.ReadLine();
            Console.WriteLine(myString);
            c = (char)Console.Read();
            Console.Write(c);
            Console.WriteLine(" comes before z");
            Console.ReadKey();
        }

Another option for writing on the console is with the use of markers in curly braces. Each marker links to a parameter which is inserted after the text. The first marker should always be 0. Copy the following code and see what it does:

       Console.WriteLine("My name is {0}, {1} {0}.""Sharp","C");

Another option is the use of formatting, you can specify the width and the justification of the text with the appropriate sign in the width number,positive values for right justification and negative values for left:

            Console.WriteLine("My name is {0,6}, {1} {0}.","Sharp""C");
            Console.WriteLine("My name is {0,-6}, {1} {0}.","Sharp""C");
Finally, you can enter a format string which can also take an optional precision value. Some of the most common format string are the following ones:

·         C = Local currency format
·         D = Decimal format. Leading zeros might be added if precision value is given.
·         E = Exponential-Scientific format. The default number of decimal places is 6, but it can be altered with the precsion value.
·         F = Fixed point format. The number of decimal places is given by the precision parameter.
·         N = Number format using “,” for thousands sepertaors and “.” for decimals.
·         X = Hexadecimal fomat.

The format string is placed axactly after the marker ( with the optional width specifier), seperated by a colon. To format an exponential with 5 decimal places use the following code:

            int myInt = 123323;
            Console.WriteLine("The result of our calculations were {0,7:E5}", myInt);

沒有留言: