C++将ASCII转换为莫尔斯电码
我一直在制作一个将字母,数字和标点转换为莫尔斯电码的程序。C++将ASCII转换为莫尔斯电码
随着字母和数字的工作,我希望它。
但与标点符号我不能让它正常工作。我希望有人可以看看我的代码并帮助我。
#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;
}
您的主要问题是,你错过了,以提供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)。
下一步的演变步骤是将底层莫尔斯数据与其表示分离。而不是'std :: string','std :: map'的映射类型可以是一个类似'MorseCode'的类,它在内部存储一系列“点”和“连字符”,例如。类型为'std :: bitset'的'private'数据成员。然后提供一个像'std :: string ToString(MorseCode const&morse_code)'这样的函数。 –
@Christian当然。让我们为newb保持简单。你是一个真正的爱好者;-)。不要忘记,对于这样的课程,“std :: set
@LasseHedegard请停止编辑我的答案。改善你的问题。 –
欢迎来到Stack Overflow。请花些时间阅读[The Tour](http://stackoverflow.com/tour),并参阅[帮助中心](http://stackoverflow.com/help/asking)中的资料,了解您可以在这里问。 –
_“但是标点符号不能让它正常工作。”_你的实际问题是什么?什么是投入,预期产出和实际产出? –
此刻我想输入:点,问号和eksklamation标记。当我输入点时,它可以很好地转换它。 但是,当我输入其他两个它给我:?U ???。 –