开发者

What does Int32.Parse do exactly?

I am just beginning to learn C#. I am reading a book and one of the examples is this:

using System;

public class Example
{
    public static void Main()
    {
        string myInput;
        int myInt;

        Console.Write("Please enter a number: ");
        myInput = Console.ReadLine();
        myInt = Int32.Parse(myInput);

        Console.WriteLine(myInt);
        Console.ReadLine();
    }
}

When i run that and enter say 'five' and hit return, i get 'input string not in correct format' error. The thing开发者_StackOverflow中文版 i don't understand is, i converted the string myInput to a number didn't i? Microsoft says that In32.Parse 'Converts the string representation of a number to its 32-bit signed integer equivalent.' So how come it doesn't work when i type the word five? It should be converted to an integer shouldn't it... confused. Thanks for advice.


'five' is not a number. It's a 4-character string with no digits in it. What parse32 is looking for is a STRING that contains numeric digit characters. You have to feed it "5" instead.


The string representation that Int32.Parse expects is a sequence of decimal digits (base 10), such as "2011". It doesn't accept natural language.

What is does is essentially this:

return 1000 * ('2' - '0')
     +  100 * ('0' - '0')
     +   10 * ('1' - '0')
     +    1 * ('1' - '0');

You can customize Int32.Parse slightly by passing different NumberStyles. For example, NumberStyles.AllowLeadingWhite allows leading white-space in the input string: " 2011".


The words representing a number aren't converted; it converts the characters that represent numbers into actual numbers.

"5" in a string is stored in memory as the ASCII (or unicode) character representation of a 5. The ASCII for a 5 is 0x35 (hex) or 53 (decimal). An integer with the value '5' is stored in memory as an actual 5, i.e. 0101 binary.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜