-
morse code convertor
I'm having troubles getting this converter to work. The getline doesn't seem to work. It skips it and goes right to the end for some reason.
Code:
#include <iostream>
#include <cstring>
using namespace std;
char *morse[36] = { ".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....",
"..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.",
"--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-",
"-.--", "--..",
"-----", ".----", "..---", "...--", "....-", ".....",
"-....", "--...", "---..", "----." };
int main()
{
int choice = 0;
while ((choice != 1) && (choice != 2))
{
cout << "Enter a choice:" << endl;
cout << "1. Text-to-Morse" << endl;
cout << "2. Morse-to-Text" << endl;
cin >> choice;
}
if (choice == 1)
{
cout << "Enter a sentence (MAX = 80 chars):" << endl;
char sentence[81];
cin.get(sentence, 81);
for (int i=0; i<=80; i++)
{
int mov = 0;
sentence[i] = toupper(sentence[i]);
if ((sentence[i] <= 90) && (sentence[i] >= 65))
mov = 65;
if ((sentence[i] <= 57) && (sentence[i] >= 22))
mov = 48;
if (sentence[i] == 32)
{
cout << " ";
}
else { cout << morse[sentence[i]-mov] << " "; }
}
}
if (choice == 2)
{
cout << "Enter a sentence in morse (MAX = 80 chars):" << endl;
char sentence[81];
cin.getline(sentence, 81);
char delims[] = " ";
char *result = strtok(sentence, delims);
while (result != NULL)
{
for (int i=0; i<=35; i++)
{
if (strcmp(result, morse[i]) == 0)
{
if (i >=26)
cout << (char)(i+22);
else
cout << (char)(i+65);
}
}
cout << " ";
result = strtok(NULL, delims);
}
}
cin >> choice;
return 0;
}
-
I think that the newline character is being entered into:
cin.get(sentence, 81);
a solution might be to use:
Code:
while ((choice != 1) && (choice != 2))
{
cout << "Enter a choice:" << endl;
cout << "1. Text-to-Morse" << endl;
cout << "2. Morse-to-Text" << endl;
cin >> choice;
cin.get();
}
-
Hey, thanks a bunch, that fixed it. Well, I used cin.ignore() instead, but thanks for pointing that problem out to me. I was amazed that after fixing that problem, the program works (seeing as I wasn't able to test it before). I was just gonna post another problem about displaying the characters in Morse to Text, but I just solved it, there needs to be parenthesis around the i+48 and i+65. Will edit that in now.
Thanks again