Spelling Alphabet – Solution

This month’s task was to create code that translates spelling from a single word into the corresponding NATO phonetic alphabet words. For input such as hello the output would be something like:

Hotel Echo Lima Lima Oscar

For my solution, I used an array of 26 pointers to represent the phonetic alphabet words. The word input is dissected one letter at a time. That letter’s offset (from A) is used to reference each phonetic alphabet word in the array. So the letter ‘B’ references element 1 in the array, “Bravo.” (Remember, arrays start numbering at element zero.)

Here’s the code:

#include <stdio.h>
#include <ctype.h>

int main()
{
    char *npa[26] = {
        "Alfa", "Bravo", "Charlie", "Delta", "Echo",
        "Foxtrot", "Golf", "Hotel", "India", "Juliett",
        "Kilo", "Lima", "Mike", "November", "Oscar",
        "Papa", "Quebec", "Romeo", "Sierra", "Tango",
        "Uniform", "Victor", "Whiskey", "Xray",
        "Yankee", "Zulu" };
    char word[24];
    int i = 0;
    char c;

    printf("Type a word: ");
    scanf("%23s",word);

    while(word[i])
    {
        c = toupper(word[i]);
        if( !isalpha(c) )
            break;
        printf("%s ",npa[c-'A']);
        i++;
    }
    putchar('\n');

    return(0);
}

The word buffer holds input text. I set its size value to 24, which is a goodly length, but not too long.

The scanf() function at Line 18 is ideal to read in a limited amount of text. That’s because scanf() stops reading at the first whitespace character. For gobbling a word, it’s perfect.

I also took advantage of the scanf() function’s %s placeholder to cap input. In this instance, only 23 characters are read by setting the %s placeholder to a width of 24. That allows for the null character (\0) at the end of the string. The potential for overflow is checked.

The next step in the code is to loop through input one character at a time. I chose a while loop at Line 20 using the current letter in the word buffer as an index. The letter is converted to uppercase by the toupper() function at Line 22. The printf() statement at Line 25 obtains the offset by subtracting the upper case letter’s ASCII value from the letter ‘A’. The value generated is used as the npa array index.

The islpha() test at Line 24 confirms that the word contains only letters of the alphabet. The scanf() function stops reading at whitespace, but it does include symbols and numbers as part of a word. The if test at Line 24 pops out of the loop once any non-alphabet character is encountered, otherwise the array index would be invalid and the program could crash with a memory error.

Your solution can be different from mine, of course. As long as the phonetic alphabet is output, and you do a bit of defensive programming to ensure that nothing has the potential of screwing up, I’d consider your efforts a success.

Leave a Reply