我一直在制作一个将字母,数字和标点符号转换为莫尔斯电码的程序。
字母和数字按照我的意愿运作。
但是由于标点符号,我无法使其正常工作。我希望有人能看看我的代码并帮助我。
#include <iostream>
#include <cstring>
#include <sstream>
using namespace std;
char ch;
string morseWord = "";
for(unsigned int i=0; i < word.length(); i++)
{
if(isalpha(word[i]))
{
ch ;
}
}
return morseWord;
}
char ch;
string morseWord = "";
for(unsigned int i=0; i < word.length(); i++)
{
if(isdigit(word[i]))
{
ch = word[i];
ch = toupper(ch);
morseWord += morseCode[ch - '0'];
morseWord += " ";
string morseWord = "";
for(unsigned int i=0; i < word.length(); i++)
{
if(ispunct(word[i]))
{
ch = word[i];
ch = toupper(ch);
morseWord += morseCode[ch - '.'];
morseWord += " ";
}
}
return morseWord;
}
int main()
{
stringstream ss;
string sentence;
string word = "";
code: " << endl;
while(ss >> ToMorse(word) << endl;
cout << PunctuationToMorse(word) << endl;
}
答案 0 :(得分:1)
您的主要问题是您错过了while()
函数中main()
循环的大括号:
while(ss >> word) { // <<<< Put an opening brace here
cout << EnglishToMorse(word) << endl;
cout << NumbersToMorse(word) << endl;
cout << PunctuationToMorse(word) << endl;
} // <<<<< ... and a closing brace here
通常更好的方法是:
使用std::map<char,std::string>
映射可以转换为莫尔斯代码的所有已知字符,并且只有一个函数来处理这些:
string CharToMorse(char c) {
static const std::map<char,std::string> morseCode = {
{ 'A', ".-" } ,
{ 'B' , "-..." } ,
{ 'C', "-.-." } ,
// ...
{ 'Z', "--.." },
{ '0', ".----" } ,
{ '1', "..---" } ,
{ '2', "...--" } ,
// ...
{ '9', "-----" } ,
{ ' ', "......." } // Consider to support spaces between words
{ '.', ".-.-.-" } ,
{ '!' , "..--.." } ,
{ '?' , "-.-.--"}
};
auto morseString = morseCode.find(toUpper(c));
if(morseString != morseCode.end()) {
return morseString->second;
}
return "";
}
并使用它:
int main() {
stringstream ss;
string sentence;
cout << "Enter a English word, number or punctuation: ";
getline(cin, sentence);
ss << sentence;
cout << "Morse code: " << endl;
char c;
while(ss >> c) {
cout << CharToMorse(c);
}
cout << endl;
}
您的实际代码存在的问题是,它假设依赖于ASCII字符代码表映射,'Z' - 'A' == 25
。
c ++标准无法保证这一点,并使您的代码不可移植(请参阅here)。