How to take input in integers and print message (numeric keypad)

1.7k views Asked by At

I have searched over the internet for this specific method but there was not anything what I was looking for. I wrote this program which takes input in integers and prints message( as in numeric keypad of cellphones). What I want to do with this program is to take input in one line as

Enter the code to crack : 454545479833165445

and the corresponding message gets printed. Rather than

Enter the code to crack :55
Enter the code to crack : 666

and prints message when I press a specific key which is -1 in this case.

  #include <iostream>
  using namespace std;

int main()
{
int a;
string n;
do{
    cout << "Enter the code to crack";
    cin >>a;

    switch (a){

    case 0:
    {


    n=n+" ";}
    break;

    case 1:
        {


    n=n+".";}
    break;

    case 11:
        {


    n=n+",";}

    break;

    case 2:{

    n=n+"a";}
    break;

    case 22:
    n=n+"b";
    break;

    case 222:
    n=n+"c";
    break;

    case 3:
    n=n+"d";
    break;

    case 33:
    n=n+"e";
    break;

    case 333:
    n=n+"f";
    break;


     case 4:
    n=n+"g";
    break;

    case 44:
    n=n+"h";
    break;

    case 444:
    n=n+"i";
    break;

     case 5:
    n=n+"j";
    break;

    case 55:
    n=n+"k";
    break;

    case 555:
    n=n+"l";
    break;


     case 6:
    n=n+"m";
    break;

    case 66:
    n=n+"n";
    break;

    case 666:
    n=n+"o";
    break;

     case 7:
    n=n+"p";
    break;

    case 77:
    n=n+"q";
    break;

    case 777:
    n=n+"r";
    break;


     case 7777:
    n=n+"s";
    break;

    case 8:
    n=n+"t";
    break;

    case 88:
    n=n+"u";
    break;

     case 888:
    n=n+"v";
    break;

    case 9:
    n=n+"w";
    break;

    case 99:
    n=n+"x";
    break;

     case 999:
    n=n+"y";
    break;

    case 9999:
    n=n+"z";
    break;}
} while(a!=-1);
cout <<"The decoded message is :" << n;

return 0;
}
1

There are 1 answers

11
Christophe On

If you want to process one signle input, assuming that the many digits that a message could contain would certainly overflow even he lognest integer type, you have to use a string input, and iterate through its chars:

string a;
string n;

cout << "Enter the code to crack";
cin >>a;   // you'll get everything, but each digit is a char 

for (int i=0; i<a.size(); i++) {
    //... process each separate digit a[i] here 
}
cout <<"The decoded message is :" << n;

Each digit a[i] is then between '0' and '9'. You'll have to take care of two difficulties:

  • the string might contain illegal caracters (for example alphanumeric), so you have to handle these cases, issuing an error message
  • each string arives separately. So no 44 anymore, but a '4' and another '4'. So you have to take into account in you ralgorithm the previous digit, to see if you have fo shift your last output letter by one, or if you have a new output letter.