什么是更好的方法来做到这一点?摩尔斯电码程序

What is a better way to do this? Morse Code Program

我用 C 语言为我的家庭作业编写了一个程序,该程序应该接收文本并通过 LED 将其翻译成摩尔斯电码。因为我知道我已经用以下内容替换了 LED 的预定闪烁长度: "It is an __." 这就像现在一样工作,我会得到充分的信任,但我的问题是是否有更好的方法来做到这一点?我知道必须有,而不是使用所有那些 'if' 语句。但我是 C 的初学者。(这段代码的唯一缺点是它很长而且你不能输入空格。)它目前的工作方式是它接受一个字符串并将其分解成单独的字母,然后在 'for' 循环检查这些单独的字母是否有相应的摩尔斯电码。让我知道你的想法。

// MorseCode_Attempt1.cpp : Defines the entry point for the console application.
//

include<stdio.h>
include<conio.h>
include<string.h>


void main() {

    char str[500];

    printf("Enter a string you want in Morse Code with underscores as spaces: ");
    scanf("%s", &str);

    int i;
    int stringLength = strlen(str);

    for (i = 0; i < stringLength; i++) {
        printf("\n[%c]\n", str[i]);


        if (str[i] == 'a') {
            printf("\nIt is an a.\n");
        }

        if (str[i] == 'b') {
            printf("\nIt is an b.\n");
        }

        if (str[i] == 'c') {
            printf("\nIt is an e.\n");
        }

        if (str[i] == 'd') {
            printf("\nIt is an d.\n");
        }

        if (str[i] == 'e') {
            printf("\nIt is an e.\n");
        }

        if (str[i] == 'f') {
            printf("\nIt is an f.\n");
        }

        if (str[i] == 'g') {
            printf("\nIt is an g.\n");
        }

        if (str[i] == 'h') {
            printf("\nIt is an h.\n");
        }

        if (str[i] == 'i') {
            printf("\nIt is an i.\n");
        }

        if (str[i] == 'j') {
            printf("\nIt is an j.\n");
        }

        if (str[i] == 'k') {
            printf("\nIt is an k.\n");
        }

        if (str[i] == 'l') {
            printf("\nIt is an l.\n");
        }

        if (str[i] == 'm') {
            printf("\nIt is an m.\n");
        }

        if (str[i] == 'n') {
            printf("\nIt is an n.\n");
        }

        if (str[i] == 'o') {
            printf("\nIt is an o.\n");
        }

        if (str[i] == 'p') {
            printf("\nIt is an p.\n");
        }

        if (str[i] == 'q') {
            printf("\nIt is an q.\n");
        }

        if (str[i] == 'r') {
            printf("\nIt is an r.\n");
        }

        if (str[i] == 's') {
            printf("\nIt is an s.\n");
        }

        if (str[i] == 't') {
            printf("\nIt is an t.\n");
        }

        if (str[i] == 'u') {
            printf("\nIt is an u.\n");
        }

        if (str[i] == 'v') {
            printf("\nIt is an v.\n");
        }

        if (str[i] == 'w') {
            printf("\nIt is an w.\n");
        }

        if (str[i] == 'x') {
            printf("\nIt is an x.\n");
        }

        if (str[i] == 'y') {
            printf("\nIt is an y.\n");
        }

        if (str[i] == 'z') {
            printf("\nIt is an z.\n");
        }

        if (str[i] == '_') {
            printf("\nIt is a SPACE.\n");
        }

    }

    return 0;

}

当你使用了很多 if's 并且在一场比赛之后你必须继续前进然后使用 if-else-if ladder 这样如果说 'b' 被发现那么它就不会检查所有其他条件。

但这里最好的解决方案是switch case

在您的for-loop.

中尝试这样的事情
switch (str[i])
{
 case 'a':
   printf("\nIt is an a.\n");
   break;

 case 'b':
   printf("\nIt is a b.\n");
   break;

  /* etc. etc. etc.*/

 default:
 //default will work when the input to the switch->here str[i] does not match any case.
   printf("\nNot a character or space!");
   break;
}

试试这个:

    for (...)
    {
       char c = str[i];
       unsigned Num;

       /* If c is a letter map it to 0..25 */
       Num = (unsigned)(toupper(c)-'A');
       if (Num<26) //This matches only with letters, as Num is unsigned.
       {
          //Each letter is represented by max four symbols 
          static const char MorseCodes[26][5]= 
          {
             "._",   //Morsecode for 'a'
             "_...", //Morsecode for 'b'
          ...
             "__..", //Morsecode for 'z'
          };
          printf("You have entered the letter %c. The morse code is %s\n", Num+'A', MorseCodes[Num]);
       }
       else 
       if (c=='_')
       {
          printf ("Space\n");
       } 
       else 
       {
          printf ("What You Are Doing?\n");
       } 
    }

鉴于您的问题,以下代码应该可以引导您朝着正确的方向前进。

请注意函数:out()、函数:delay()、#define ON 和#define OFF 取决于您的环境。

include<stdio.h>
//include<conio.h> -- dont include header files that are not used
include<string.h>

// adjust DELAY_UNIT as necessary
#define DELAY_UNIT (1000)
#define DOT_TIME   (1)
#define DASH_TIME  (3)
#define INTER_WORD_TIME (7)
#define INTER_CHAR_TIME (3)
#define DOT        ('.')
#define DASH       ('-')

// OP needs to define function 'out()', LED, ON, OFF and DELAY_UNIT
// to suit the environment

// prototypes
char *findIndex( struct morseStruct *morse, char ch);
void MorseToLed( char *sequencePtr);
void delay( long unsigned int );

/*
 * If the duration of a dot is taken to be one unit
 * then that of a dash is three units.
 *
 * The space between the components of one character is one unit,
 *
 * between characters is three units and between words seven units.
 *
 * To indicate that a mistake has been made and for the receiver to delete the last word,
 * send ........ (eight dots).
 */

// see <http://morsecode.scphillips.com/morse2.html> for source list
// of morse code char formats

struct morseStruct
{
    char  searchChar;
    char *morseSequence;
};

static const struct morseStruct *alphanumeric[] =
{
    {'A', ",-"   };
    {'B', "-..." };
    {'C', "-.-." };
    ...  // add other alphameric definitions here
    {0, NULL};
};

static const struct morseStruct *punctuation[] =
{
    {'.', ".-.-.-" }; // period
    {',', "--..--" }; // comma
    {':', "---..." }; // colon
    {'?', "..--.." }; // question mark
    {'\'', ".----."}; // apostrophe (note: must escape certain characters)
    {'-', "-....-" }; // hyphen
    {'/', "-..-."  }; // right slash
    {'\"', ".-..-."}; // quotation mark
    {'@', ".--.-." }; // at sign
    {'=', "-...-"  }; // equals sign
    {0, NULL};
};

static const struct morseStruct *prosigns[] =
{
    ... // add prosigns here
    {0, NULL};
};



int main( void )
{

    char str[500];

    printf("Enter a string you want in Morse Code with underscores as spaces: ");
    if( NULL == fgets(str, sizeof( str ), stdin );
    { // then fgets failed
        perror( "fgets for user input string failed");
        exit( EXIT_FAILURE );
    }

    // implied else, fgets successful

    //eliminate trailing newline, if any
    if( char *pNewline = strstr( str, "\n")
    {
        pNewline = '\n';
    }

    size_t stringLength = strlen(str);
    int i;

    for (i = 0; i < stringLength; i++)
    {
        printf("\n[%c]\n", str[i]);


        // handle special cases
        if '_' == str[i] )
        { // then between words
            //out(LED, OFF); // should already be OFF
            delay( INTER_WORD_TIME*DELAY_UNIT );
            continue;
        }

        int sequencePtr;

        if( NULL == (sequencePtr = findIndex( alphaNumeric, str[i] ) ) )
        {// then not alphanumeric value
            if( NULL == (sequencePtr = findIndex( punctuation, str[i] ) ) )
            { // then not punctuation value
                if( NULL == (sequencePtr = findIndex( prosigns, str[i] ) ) )
                { // then not prosign value
                    printf( "char: %0X is not recognized\n", str[i]);
                    continue;
                }
            }
        }

        MorseToLed (sequencePtr);
    } // end for

    return 0;
} // end function: main


char *findIndex( struct morseStruct *morse, char ch)
{
    char *pSequence = NULL;
    int  i = 0;

    while( NULL != morse[i].morseSequence )
    {
        if( ch == morse[i].searchChar )
        { // then found desire morse code sequence
            pSequence = morse[i].morseSequence;
            break;
        }
        i++;
    }
    return( pSequence );
} // end function: findIndex


void MorseToLed( char *sequencePtr)
{
    size_t i = strlen( sequencePtr );

    for( size_t j = 0; j<i; j++)
    {
        if( DOT == sequencePtr[j] )
        {
            out(LED, ON);
            delay( DOT_TIME * DELAY_UNIT );
            out(LED, OFF);
        }
        else if( DASH == sequencePtr[j] )
        {
            out(LED, ON);
            delay( DASH_TIME * DELAY_UNIT );
            out(LED, OFF);
        }
        delay( DELAY_UNIT ); // delay between components of one char
    } // end for

    delay( INTER_CHAR_TIME * DELAY_UNIT ); // delay between characters
} // end function: MorseToLed


void delay( long unsigned int delayUnits )
{
    ?????
} // end function: delay