Wednesday, January 25, 2012

3.3. Character data type

We also have a data type to store a single letter. It is named "char":

char letter;

Assigning values is simple: we indicate them using single quotes:

letter = 'a';

If we want to read values from the keyboard, we can make it similar in a similar way to the previous cases: read an entire sentence with ReadLine and convert it using Convert.ToChar:

letter = Convert.ToChar(Console.ReadLine());

A program to assign an starting value to a letter, display it, read a new letter entered by the user, and show it again, might be:

/*---------------------------*/
/*  C# Example #29:          */
/*  example29.cs             */
/*                           */
/*  "char" data type         */
/*                           */
/*  Intro to C#,             */
/*    Nacho Cabanes          */
/*---------------------------*/

using System;

public class Example29
{
    public static void Main()
    {
        char letter;
       
        letter = 'a';
        Console.WriteLine("The letter is {0}", letter);
       
        Console.WriteLine("Enter a new letter");
        letter = Convert.ToChar(Console.ReadLine());
        Console.WriteLine("Now the letter is {0}", letter);
    }
}


No comments:

Post a Comment