Interactive game using cin

eXceed69 0 Tallied Votes 153 Views Share

An interactive program using std::cin, std::cout, while loop and switch which will take from user no. 0 to 9 and print the number in characters. (eg. if user inters 0 the program shall respond You Have Entered : ZERO)

If any negative number is given program should terminate.

#include <iostream>
#include <cstring> // used for strcpy fuction.
 
int main()
{
     //to store integer
     int num = 0;
     char numInString[10];
          
     //infinite while loop for interactivity
    while (1)
    { 
          //Ask user to enter the number between 0 and 9. Negative to exit.
        std::cout << "Please Enter an Integer between 0 and 9 : ";
          
        //Store the variable entered by the user.
        std::cin >> num;
 
          //if the variable entered is negative, break the loop.
        if (num < 0) break;
          
          //use switch for printing the character variables.
        switch (num)
        {
               case 0 : strcpy (numInString, "ZERO");
                        break;
               case 1 : strcpy (numInString, "ONE");
                        break;
               case 2 : strcpy (numInString, "TWO");
                        break;
               case 3 : strcpy (numInString, "THREE");
                        break;
               case 4 : strcpy (numInString, "FOUR");
                        break;
               case 5 : strcpy (numInString, "FIVE");
                        break;
               case 6 : strcpy (numInString, "SIX");
                        break;
               case 7 : strcpy (numInString, "SEVEN");
                        break;
               case 8 : strcpy (numInString, "EIGHT");
                        break;
               case 9 : strcpy (numInString, "NINE");
                        break;
               default : strcpy (numInString, "INVALID");
                         break;
        }
 
          //show user what they have entered.
        std::cout << "You Have Entered : " << numInString << ".\n";
    }
    return 0;
}
Ene Uran 638 Posting Virtuoso

Very nice example of switch case!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.