Saturday, May 22, 2010

Program using c++ (switch case statemant)?

Write a program to print the given Number in Words using Switch case statement. The


Program has to accept only numbers from 0 to 9. It has to display wrong input for other


values.


Example


Input Output


4 Four


5 Five

Program using c++ (switch case statemant)?
This is a Quick 'n Dirty C# Console App, but I'm sure it can be ported to C++ with little difficulty.








using System;


using System.Text;


using System.Text.RegularExpressions;





namespace MyProgram


{


class Program


{


static void Main(string[] args)


{


Console.WriteLine("Please enter a number between 0 and 9: ");


string input = Console.ReadLine();


Console.WriteLine("You entered " + NumToString(input));


Console.WriteLine("\nPress Enter key to exit.");


Console.ReadLine();


}





private static string NumToString(string number)


{


try


{


switch (int.Parse(number))


{


case 1:


return "One";





case 2:


return "Two";





case 3:


return "Three";





case 4:


return "Four";





case 5:


return "Five";





case 6:


return "Six";





case 7:


return "Seven";





case 8:


return "Eight";





case 9:


return "Nine";





default:


return "a number that was not between 0 and 9";


}


}


catch


{


return " a non-numeric value!";


}


}


}


}
Reply:if this is homework than do it yourself.





If this isn't then you're using a really stupid algorithm. Simple division and modulus operations can give you a much better output although thats still not the best way.





You could just use that atoi function or strtol.


No comments:

Post a Comment