C# Programming/The .NET Framework/Console Programming

From Wikibooks, open books for an open world
< C Sharp Programming | The .NET Framework
Jump to: navigation, search

Contents

[edit] Console Programming

[edit] Output

The example program below shows a couple of ways to output text:

using System;

public class HelloWorld
{
   public static void Main()
   {
       Console.WriteLine("Hello World!");             // relies on "using System;"
       Console.Write("This is");
       Console.Write("... my first program!\n");
       System.Console.WriteLine("Goodbye World!");    // no "using" statement required
   }
}

The above code displays the following text:

Hello World!
This is... my first program!
Goodbye World!

That text is output using the System.Console class. The using statement at the top allows the compiler to find the Console class without specifying the System namespace each time it is used.

The middle lines use the Write() method, which does not automatically create a new line. To specify a new line, we can use the sequence backslash-n (\n). If for whatever reason we wanted to really show the \n character instead, we add a second backslash (\\n). The backslash is known as the escape character in C# because it is not treated as a normal character, but allows us to encode certain special characters (like a new line character).

[edit] Input

Input can be gathered in a similar method to outputing data using the Read() and ReadLine methods of that same System.Console class:

using System;
public class ExampleClass
{
   public static void Main()
   {
       Console.WriteLine("Greetings!  What is your name?");
       Console.Write("My name is: ");
       string name = Console.ReadLine();

       Console.WriteLine("Nice to meet you, " + name);
       Console.Read();
   }
}

The above program requests the user's name and displays it back. The final Console.Read() waits for the user to enter a key before exiting the program.

[edit] Error

The Error output is used to divert error specific messages to the console. To a novice user this may seem fairly pointless, as this achieves the same as Output (as above). If you decide to write an application that runs another application (for example a scheduler), you may wish to monitor the output of that program - more specifically, you may only wish to be notified only of the errors that occur. If you coded your program to write to the Console.Error stream whenever an error occurred, you can tell your scheduler program to monitor this stream, and feedback any information that is sent to it. Instead of the Console appearing with the Error messages, your program may wish to log these to a file.

You may wish to revisit this after studying Streams and after learning about the Process class.

[edit] Command line arguments

Command line arguments are values that are passed to a console program before execution. For example, the Windows command prompt includes a copy command that takes two command line arguments. The first argument is the original file and the second is the location or name for the new copy. Custom console applications can have arguments as well.

using System;

public class ExampleClass
{
   public static void Main(string[] args)
   {
       Console.WriteLine("First Name: " + args[0]);
       Console.WriteLine("Last Name: " + args[1]);
       Console.Read();
   }
}

If the program above code is compiled to a program called username.exe, it can be executed from the command line using two arguments, e.g. "Bill" and "Gates":

C:\>username.exe Bill Gates

Notice how the Main() method above has a string array parameter. The program assumes that there will be two arguments. That assumption makes the program unsafe. If it is run without the expected number of command line arguments, it will crash when it attempts to access the missing argument. To make the program more robust, we can check to see if the user entered all the required arguments.

using System;

public class Test
{
   public static void Main(string[] args)
   {
       if(args.Length >= 1)
           Console.WriteLine(args[0]);
       if(args.Length >= 2)
           Console.WriteLine(args[1]);
   }
}

Try running the program with only entering your first name or no name at all. The args.Length property returns the total number of arguments. If no arguments are given, it will return zero.

You are also able to group a single argument together by using the quote marks (""). This is particularly useful if you are expecting many parameters, but there is a requirement for including spaces (e.g. file locations, file names, full names etc.)

using System;
 
class Test
{
   public static void Main(string[] args)
   {
      for (int index = 0; index < args.Length; index++)
      {
         Console.WriteLine((index + 1) + ": " + args[index]);
      }
   }
}
C:\> Test.exe Separate words "grouped together"
1: Separate
2: words
3: grouped together

[edit] Formatted output

Console.Write() and Console.WriteLine() allow you to output a text string, but also allows writing a string with variable substitution.

These two functions normally have a string as the first parameter. When additional objects are added, either as parameters or as an array, the function will scan the string to substitute objects in place of tokens.

For example:

{
  int i = 10;
  Console.WriteLine("i = {0}", i);
}

The {0} is identified by braces, and refers to the parameter index that needs to be substituted. You may also find a format specifier within the braces, which is preceded by a colon and the specifier in question (e.g. {0:G}).

[edit] Example program that rounds numbers

This is a small example that rounds a number to a string. It is necessary to round to a string, as significant figures may be trailing zeros that would disappear, if a number format would be used. Here is the code and its call:

    class Maths
    {
        /// <summary>
        ///     The string of zeros
        /// </summary>
        private static String m_strZeros = "000000000000000000000000000000000";
        /// <summary>
        ///     The minus sign
        /// </summary>
        public const char m_cDASH = '-';
 
        /// <summary>
        ///     Determines the number of digits before the decimal point
        /// </summary>
        /// <param name="cDecimal">
        ///     Language-specific decimal separator
        /// </param>
        /// <param name="strValue">
        ///     Value to be scrutinised
        /// </param>
        /// <returns>
        ///     Nr. of digits before the decimal point
        /// </returns>
        private static ushort NrOfDigitsBeforeDecimal(char cDecimal, String strValue)
        {
            short sDecimalPosition = (short)strValue.IndexOf(cDecimal);
            ushort usSignificantDigits = 0;
 
            if (sDecimalPosition >= 0)
            {
                strValue = strValue.Substring(0, sDecimalPosition + 1);
            }
 
            for (ushort us = 0; us < strValue.Length; us++)
            {
                if (strValue[us] != m_cDASH) usSignificantDigits++;
 
                if (strValue[us] == cDecimal)
                {
                    usSignificantDigits--;
                    break;
                }
            }
 
            return usSignificantDigits;
        }
 
        /// <summary>
        ///     Rounds to a fixed number of significant digits
        /// </summary>
        /// <param name="d">
        ///     Number to be rounded
        /// </param>
        /// <param name="usSignificants">
        ///     Requested significant digits
        /// </param>
        /// <returns>
        ///     The rounded number
        /// </returns>
        public static String Round(char cDecimal,
            double d,
            ushort usSignificants)
        {
            StringBuilder value = new StringBuilder(Convert.ToString(d));
 
            short sDecimalPosition = (short)value.ToString().IndexOf(cDecimal);
            ushort usAfterDecimal = 0;
            ushort usDigitsBeforeDecimal =
                NrOfDigitsBeforeDecimal(cDecimal, value.ToString());
 
            if (usDigitsBeforeDecimal == 1)
            {
                usAfterDecimal = (d == 0) ? usSignificants
                    : (ushort)(value.Length - sDecimalPosition - 2);
            }
            else
            {
                if (usSignificants >= usDigitsBeforeDecimal)
                {
                    usAfterDecimal =
                        (ushort)(usSignificants - usDigitsBeforeDecimal);
                }
                else
                {
                    double dPower = Math.Pow(10,
                        usDigitsBeforeDecimal - usSignificants);
 
                    d = dPower*(long)(d/dPower);
                }
            }
 
            double dRounded = Math.Round(d, usAfterDecimal);
            StringBuilder result = new StringBuilder();
 
            result.Append(dRounded);
            ushort usDigits = (ushort)result.ToString().Replace(
                Convert.ToString(cDecimal), "").Replace(
                Convert.ToString(m_cDASH), "").Length;
 
            // Add lagging zeros, if necessary:
            if (usDigits < usSignificants)
            {
                if (usAfterDecimal != 0)
                {
                    if (result.ToString().IndexOf(cDecimal) == -1)
                    {
                        result.Append(cDecimal);
                    }
 
                    int i = (d == 0) ? 0 : Math.Min(0, usDigits - usSignificants);
 
                    result.Append(m_strZeros.Substring(0, usAfterDecimal + i));
                }
            }
 
            return result.ToString();
        }
    }
 
    class Program
    {
        static void Main(string[] args)
        {
            //char cDecimal = '.';    // for English cultures
            char cDecimal = ',';    // for German cultures
            List<double> l_dValue = new List<double>();
            ushort usSignificants = 5;
 
            l_dValue.Add(0);
            l_dValue.Add(0.000640589);
            l_dValue.Add(-0.000640589);
            l_dValue.Add(-123.405009);
            l_dValue.Add(123.405009);
            l_dValue.Add(-540);
            l_dValue.Add(540);
            l_dValue.Add(-540911);
            l_dValue.Add(540911);
            l_dValue.Add(-118.2);
            l_dValue.Add(118.2);
            l_dValue.Add(-118.188);
            l_dValue.Add(118.188);
            l_dValue.Add(-130.76994323730469);
            l_dValue.Add(130.76994323730469);
 
            foreach (double d in l_dValue)
            {
                Console.WriteLine("d = Maths.Round('" +
                    cDecimal + "', " + d + ", " + usSignificants +
                    ") = " + Maths.Round(
                    cDecimal, d, usSignificants));
            }
 
            Console.Read();    // To prevent closing of the console window
        }
Personal tools
Namespaces
Variants
Actions
Navigation
Community
Toolbox
Sister projects
Print/export