-1

I just started the CodeCademy C# course this evening and have a question. I am in the converting data type section and was able to "pass" the exercise but the code did not output what I expected. When I run the program it prompts "Whats your favorite number?" if I input 5 it does what I expected and outputs "your favorite number is 5". What I don't understand is if I input five, the program throws an incorrect format error. I thought the Convert.ToInt32() method was supposed to take a string input and convert it to its corresponding integer? Any help understanding what I am doing or thinking wrong is appreciated.

static void Main(string[] args) {

   // Ask user for fave number
   Console.Write("Enter your favorite number?: ");

   // Turn that answer into an integer

  int faveNumber = Convert.ToInt32(Console.ReadLine());
  Console.WriteLine("your favorite number is:" + faveNumber);

}
yusuzech
  • 5,896
  • 1
  • 18
  • 33
Tyler7498
  • 3
  • 4

2 Answers2

7

Convert.ToInt32() takes a string that only contains numeric characters. Anything else is an error. Converting english-language words (such as "five") into a numeric value isn't what Convert.ToInt32() does.

If you want to convert strings such as "one hundred and fifteen" into an int, it's a little more complicated. Here's an answer I wrote for fun a while ago that does just this (albeit to long rather than int):

https://stackoverflow.com/a/11278412/14357

spender
  • 117,338
  • 33
  • 229
  • 351
1

Convert.ToInt32() only able to convert digit character. It can't recognize english vocab. If you want to recognize the english language, you can write the similar function to do the work.

   private static int ConvertToNumber(string input)
    {
        switch (input)
        {
            case "Five":
                return 5;
                // do the remaining work

            default:
                return 0;
        }
    }
ReCoder
  • 11
  • 2
  • This is not a good solution. What if I want "two billion one hundred and forty-seven million, four hundred and eighty-three thousand, six hundred and forty-seven"? Should I have two billion cases? What about where the user just inputs "2147483647"? – ProgrammingLlama Jul 31 '19 at 04:49
  • Yes of course it is not a good solution for "two billion one hundred and forty-seven million, four hundred and eighty-three thousand, six hundred and forty-seven". Just provide the idea based on the use case. You may refer to spender answer for your question. – ReCoder Jul 31 '19 at 05:37