Console I/O C# Help

By this point, you should have a basic familiarity with C#’s data types; as well as some knowledge of how the thread-of-control moves through a program that manipulates those data types. In this chapter, you have also use several of the Console class’s static methods used for reading and writing data. Because these methods are so useful when writing basic C#programs, this section quickly reviews them in more detail.

To read a line of text from the console window, you 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 co responding methods for writing to the console, which you have already used extensively:

  1. Console. Write ( )-Writes the spe ..ed value to the console window.
  2.  Console. WriteLine ( )-This does me same, but adds a newline character at the end of the output.

Various forms (overloads) of these methods exist for all of the predefined types (including object), so in most cases you don’t have to convert values to strings before you 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 () 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, {O} represents the first parameter in the list. Consider the following code:

You can also specify a width for the value, and justify the text within that width, using positive values for right-justification and negative values for left-justification. To do this, use the format (n, w}, where n
is the parameter index and w is the width value:

Finally, you can also add a format string, together with an optional precision value. you can define your own format strings. However, the main ones in use for the predefined types are shown in the following table.

Note that the format strings are normally case insensitive, except for e/E.

If you want to use a format string, you should place it immediately after the marker that gives the parameter number and field width, and separate it with a colon. For example, to format a decimal value
as currency for the computer’s locale, with precision to two decimal places, you would use C2:

This displays as .23, because the  symbol is ignored if there is no character in that place, and zeros will either be replaced by the character in that position if there is one or be printed as a zero.

Posted on October 27, 2015 in C# Basics

Share the Story

Back to Top
Share This