有什么更好的方法呢?摩尔斯电码计划

时间:2015-09-12 03:52:40

标签: c morse-code

我在C中为我的作业编写了一个程序,该程序应该采用文本并通过LED将其转换为摩尔斯电码。要知道我已经用LED替换了预定的闪烁长度:“这是一个__”。这是现在的工作,我会得到充分的信任,但我的问题是,是否有更好的方法来做到这一点?我知道必须有,而不是使用所有那些“如果”的陈述。但我是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;

}

3 个答案:

答案 0 :(得分:2)

当您使用大量if's并且在一场比赛后,您必须继续前进,然后使用if-else-if ladder,这样如果说&#39; b&#39;找到然后它不会检查所有其他条件。

但这里最好的解决方案是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;
}

答案 1 :(得分:1)

试试这个:

    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");
       } 
    }

答案 2 :(得分:0)

根据您的问题,以下代码应引导您朝着正确的方向前进。

请注意,函数: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