Search code examples
c++switch-statementcharacterdigits

Switch statement to convert a word into digits ? C++


Right now I was able to make a program that only converts the first letter of a word into its corresponding digit but it stops after the first conversion. If I don't use a 'break' after each 'case', the program just goes on to output the following cases which is not what I want.

switch (nameChar) { case 'a': case 'b': case 'c': cout << "1"; break;

Can I make this program repeat for the following letter of the word until there are no more letters in the word ?

#include <iostream>
#include<string>
using namespace std;

int main () {

    char nameChar;

    cout << "enter a name";
    cin >> nameChar;

            switch (nameChar)
        {
            case 'a': case 'b': case 'c':
                cout << "1";
                break;
            case 'd': case 'e': case 'f':
                cout << "2";
                break;
            case 'g': case 'h': case 'i':
                cout << "3";
                break;
            case 'j': case 'k': case 'l':
                cout << "4";
                break;
            case 'm': case 'n': case 'o':
                cout << "5";
                break;
            case 'p': case 'q': case 'r':
                cout << "6";
                break;
            case 's': case 't': case 'u':
                cout << "7";
                break;
            case 'v': case 'w': case 'x':
                cout << "8";
                break;
            case 'y': case 'z':
                cout << "9";
                break;
            default:
                return 0;

                char nameChar;

                cout << nameChar;
        }
    }

Solution

  • You should use something like this inside main:

    string name;
    cout << "enter a name";
    cin >> name;
    for (auto letter : name) {
        switch (letter) {
            //rest of your case
        }
    }
    

    Because char is meant to store only one letter, string is a class you want to use for whole strings.