You are here:

C++/Homework Help

Advertisement


Question
I have to do a program that converts telephone numbers into letters. If the user enters more than seven letters, then process only the first seven letters. My program compiles and works somewhat properly but it is processing more than 7 numbers. I tried to use a counter but I cannot figure out how to stop it from processing numbers past 7. My code is below. Please help me.

#include <iostream>
#include <stdlib.h>

using namespace std;

int main()
{
  char letter;                          //Line 1

  cout << "Program to convert "
      << "letters to their corresponding "
      << "telephone digits." << endl;        //Line 2

 do {
  cout << "To stop the program enter #."
      << endl;                         //Line 3

  cout << "Enter letters used for a phone number and press Enter:";               //Line 4
  cin >> letter;                        //Line 5

  // WE USE THIS TO ITERATE THROUGH THE CODE
  int counter = 0;
  while (letter != '\n')
  {
     if (counter == 3 && counter != 0)
        cout << "-";
     if ( letter == '#')  break;
     if ((letter >= 'A' && letter <= 'Z')      //Line 10
       || (letter >= 'a' && letter <= 'z' ) )
        switch (letter)                  //Line 11
        {
        case 'A':
        case 'B':
        case 'C':
        case 'a':
        case 'b':
        case 'c':
        cout << "2";            //Line 12
        break;      
                          //Line 13
        case 'D':
        case 'E':
        case 'F':
        case 'd':
        case 'e':
        case 'f':
        cout << "3";           //Line 14
        break;      
                          //Line 15
        case 'G':
        case 'H':
        case 'I':
        case 'g':
        case 'h':
        case 'i':
        cout << "4";           //Line 16
        break;   
                             //Line 17
        case 'J':
        case 'K':
        case 'L':
        case 'j':
        case 'k':
        case 'l':
        cout << "5";           //Line 18
        break;   
                             //Line 19
        case 'M':
        case 'N':
        case 'O':
        case 'm':
        case 'n':
        case 'o':
        cout << "6";           //Line 20
        break;   
                             //Line 21
        case 'P':
        case 'Q':
        case 'R':
        case 'S':
        case 'p':
        case 'q':
        case 'r':
        case 's':
        cout << "7";           //Line 22
        break;   
                             //Line 23
        case 'T':
        case 'U':
        case 'V':
        case 't':
        case 'u':
        case 'v':
        cout << "8";           //Line 24
        break;
                                //Line 25
        case 'W':
        case 'X':
        case 'Y':
        case 'Z':
        case 'w':
        case 'x':
        case 'y':
        case 'z':
        cout << "9";           //Line 26
           
        case ' ':
        case '\t':
          break;
     }  // end of switch statement
     else                          //Line 27
        cout << "Invalid input." << endl;    //Line 28

     cin >> letter;                     //Line 32
     counter ++; // INCREMENT OUR COUNTER
    }  //end of while loop for letters
    cout << endl;

  } while (letter != '#');//no more input

  system ("Pause");
  return 0;
}


Answer
OK as this is homework I am not just going to fix your code for you.

I will however make a few points  and show some partial code to help you move forward.

Firstly, it seems to me that you have not read the assignment statement carefully enough, or have made a mistake typing your question. Your question starts:

   "I have to do a program that converts telephone numbers into letters."

Note there the task is to:

   "converts telephone numbers into letters."

That is read in _numbers_ and output _letters_.

You then go on to say:

   "If the user enters more than seven letters, then process only the first seven letters."

Which implies reading in _letters_ and outputting _numbers_.

This contradicts the first statement of the requirements.

Looking at the code you seem to be converting letters to numbers - which is easier as  this is a one to one mapping whereas the number to letter conversion is a one to many mapping.

OK so the next point I would make is that maybe the program should be used like so:

   Enter up to 7 letters to convert (space, tab or hyphen may be used as separators): aBc DeF m
   
   The telephone number equivalent is: 222 333 6

Whereas a quick look at you code suggests it works like so:

   Enter letters used for a phone number and press Enter: a
   2Enter letters used for a phone number and press Enter: B
   2Enter letters used for a phone number and press Enter: c
   2

etc.

So first off try reading the whole input as one string then process each letter in that string:

   #include <string>       // For C++ library std::string type
   
   ...
   
   using namespace std;
   
   ...
   
   string  telephoneIdAsLetters;
   cout << "Enter up to 7 letters to convert (space, tab or hyphen may be used as separators): ";
   cin >> telephoneIdAsLetters;
   
   unsigned int lettersProcessedCount(0);
   unsigned in  characterIndex(0);
   
   unsigned int const MaximumLettersToProcess(7);
   
   while ( characterIndex < telephoneIdAsLetters.size() && lettersProcessedCount<=MaximumLettersToProcess )
   {
       switch ( telephoneIdAsLetters[characterIndex++] )
       {
           case 'A':
           case 'B':
           case 'C':
           case 'a':
           case 'b':
           case 'c':
               cout << "2";
               ++lettersProcessedCount;
               break;      

           case 'D':
           case 'E':
           case 'F':
           case 'd':
           case 'e':
           case 'f':
               cout << "3";
               ++lettersProcessedCount;
               break;
           
           ...
           
           case ' ':
           case '\t':
           case '-':
              break; // no output, not a letter so does _not_ increment lettersProcessedCount
              
           default:
               cout << "\nInvalid input." << endl;
               break;
       }
   }

Notice that you can use the default clause of a switch statement to handle all unmatched cases. So the switch statement now does all the character handling.

For each of the letter case groups you increment the count of letters process so far and this is checked as one of the loop continuation conditions.

As all the input is now read in one go you have no need for the '#' end of input handling.

You will have to complete my partial code and add in the logic to process outputting '-' every 3 numbers output. Note that the number of numbers output is equal to the number of letters processed.

Also note that you existing check is wrong:

   if (counter == 3 && counter != 0)

Firstly as 3 is not equal zero the check for counter == 3 is redundant, hence the above is equivalent to:

   if (counter != 0)

Which is obviously wrong as it outputs a '-' for _all_ counts except zero - presumably after every input except the first.

Hint: you want to output the '-' after the number of numbers output is 3 and 6. Try taking the modulus (remainder) of lettersProcessedCount divided by 3 ( lettersProcessedCount % 3 ) and check for the result being zero. You _will_ have to exclude the case where lettersProcessedCount==0 in this case though!

Once you have the basics working you could try building a string to hold all output, rather than outputting the characters directly, and _only_ output this string _if_ no invalid characters were entered.

Hope this helps.  

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Ralph McArdell

Expertise

I am a software developer with more than 15 years C++ experience and over 25 years experience developing a wide variety of applications for Windows NT/2000/XP, UNIX, Linux and other platforms. I can help with basic to advanced C++, C (although I do not write just-C much if at all these days so maybe ask in the C section about purely C matters), software development and many platform specific and system development problems.

Experience

My career started in the mid 1980s working as a batch process operator for the now defunct Inner London Education Authority, working on Prime mini computers. I then moved into the role of Programmer / Analyst, also on the Primes, then into technical support and finally into the micro computing section, using a variety of 16 and 8 bit machines. Following the demise of the ILEA I worked for a small company, now gone, called Hodos. I worked on a part task train simulator using C and the Intel DVI (Digital Video Interactive) - the hardware based predecessor to Indeo. Other projects included a CGI based train simulator (different goals to the first), and various other projects in C and Visual Basic (er, version 1 that is). When Hodos went into receivership I went freelance and finally managed to start working in C++. I initially had contracts working on train simulators (surprise) and multimedia - I worked on many of the Dorling Kindersley CD-ROM titles and wrote the screensaver games for the Wallace and Gromit Cracking Animator CD. My more recent contracts have been more traditionally IT based, working predominately in C++ on MS Windows NT, 2000. XP, Linux and UN*X. These projects have had wide ranging additional skill sets including system analysis and design, databases and SQL in various guises, C#, client server and remoting, cross porting applications between platforms and various client development processes. I have an interest in the development of the C++ core language and libraries and try to keep up with at least some of the papers on the ISO C++ Standard Committee site at http://www.open-std.org/jtc1/sc22/wg21/.

Education/Credentials

©2012 About.com, a part of The New York Times Company. All rights reserved.