Converting Numeric Strings to Their Internal Representation


Before leaving the topic of I/O, we will examine a technique that is useful when reading numeric strings. As you know, C#’s WriteLine( ) method provides a convenient way to output various types of data to the console, including numeric values of the built-in types, such as int and double. Thus, WriteLine( ) automatically converts numeric values into their human-readable form. However, C# does not provide the reverse: an input method that reads and converts strings representing numeric values into their internal, binary format. For example, there is no way to enter at the keyboard a string such as “100” and have it automatically converted into its corresponding binary value that is able to be stored in an int variable. To accomplish this task, you will need to use a method that is defined for all of the built-in numeric types: Parse( ).

Before we begin, it is necessary to state an important fact: all of C#’s built-in types, such as int and double, are actually just aliases (that is, other names for) structures defined by the .NET Framework. In fact, Microsoft explicitly states that the C# type and .NET structure type are indistinguishable. One is just another name for the other. Because C#’s value types are supported by structures, the value types have members defined for them.

For the numeric types, the .NET structure names and their C# keyword equivalents are shown here:

.NET Structure Name C#

Name

Decimal

decimal

Double

double

Single

float

Int16

short

Int32

int

Int64

long

UInt16

ushort

UInt32

uint

UInt64

ulong

Byte

byte

Sbyte

sbyte

The structures are defined inside the System namespace. Thus, the fully qualified name for Int32 is System.Int32. These structures offer a wide array of methods that help fully integrate the value types into C#’s object hierarchy. As a side benefit, the numeric structures also define static methods that convert a numeric string into its corresponding binary equivalent. These conversion methods are shown here. Each returns a binary value that corresponds to the string.

Structure

Conversion Method

Decimal

static decimal Parse(string str)

Double

static double Parse(string str)

Single

static float Parse(string str)

Int64

static long Parse(string str)

Int32

static int Parse(string str)

Int16

static short Parse(string str)

UInt64

static ulong Parse(string str)

UInt32

static uint Parse(string str)

UInt16

static ushort Parse(string str)

Byte

static byte Parse(string str)

SByte

static sbyte Parse(string str)

The Parse( ) methods will throw a FormatException if str does not contain a valid number as defined by the invoking type. ArgumentNullException is thrown if str is null, and OverflowException is thrown if the value in str exceeds the invoking type.

The parsing methods give you an easy way to convert a numeric value, read as a string from the keyboard or a text file, into its proper internal format. For example, the following program averages a list of numbers entered by the user. It first asks the user for the number of values to be averaged. It then reads that number using ReadLine( ) and uses Int32.Parse( ) to convert the string into an integer. Next, it inputs the values, using Double.Parse( ) to convert the strings into their double equivalents.

 // This program averages a list of numbers entered by the user. using System; using System.IO; class AvgNums {   public static void Main() {     string str;     int n;     double sum = 0.0;     double avg, t;     Console.Write("How many numbers will you enter: ");     str = Console.ReadLine();     try {       n = Int32.Parse(str);     }     catch(FormatException exc) {       Console.WriteLine(exc.Message);       n = 0;     }     catch(OverflowException exc) {       Console.WriteLine(exc.Message);       n = 0;     }     Console.WriteLine("Enter " + n + " values.");     for(int i=0; i < n; i++)  {       Console.Write(": ");       str = Console.ReadLine();       try {         t = Double.Parse(str);       } catch(FormatException exc) {         Console.WriteLine(exc.Message);         t = 0.0;       }       catch(OverflowException exc) {         Console.WriteLine(exc.Message);         t = 0;       }       sum += t;     }     avg = sum / n;     Console.WriteLine("Average is " + avg);   } }

Here is a sample run:

 How many numbers will you enter: 5 Enter 5 values. : 1.1 : 2.2 : 3.3 : 4.4 : 5.5 Average is 3.3

One last point: You must use the right parsing method for the type of value you are trying to convert. For example, trying to use Int32.Parse( ) on a string that contains a floating-point value will not produce the desired result.




C# 2.0(c) The Complete Reference
C# 2.0: The Complete Reference (Complete Reference Series)
ISBN: 0072262095
EAN: 2147483647
Year: 2006
Pages: 300

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net