gpt4 book ai didi

c++ - 单词之间的摩尔斯电码空格问题

转载 作者:行者123 更新时间:2023-11-30 04:43:15 26 4
gpt4 key购买 nike

我在尝试让我的代码将空格字符转换为“xx”时遇到问题。我已经设置好了,所以在每个字母之后都有一个 x 来分隔字母,但我无法完全理解下面的内容来处理单词之间的空格。

#include <iostream>
#include <cstring>
#include <sstream>
#include <algorithm>
using namespace std;

string translate(string word)
{
string morseCode[] = { ".-x", "-...x", "-.-.x", "-..x", ".x", "..-.x",
"--.x", "....x", "..x", ".---x", "-.-x", ".-..x", "--x", "-.x", "---x",
".--.x", "--.-x", ".-.x", "...x", "-x", "..-x", "...-x", ".--x", "-..-x",
"-.--x", "--..x" };
char ch;
string morseWord = " ";
//string morseWord = " " == "xx";


for (unsigned int i = 0; i < word.length(); i++)
{
if (isalpha(word[i]))
{
ch = word[i];
ch = toupper(ch);
morseWord += morseCode[ch - 'A'];
morseWord += morseCode[ch = ' '] == "xx";
//morseWord += "xx";
//morseWord += " " == "xx";
}

}
return morseWord;
}

int main()
{
stringstream stringsent;
string sentence;
string word = "";

cout << "Please enter a sentence: ";
getline(cin, sentence);
stringsent << sentence;
cout << "The morse code translation for that sentence is: " << endl;
while (stringsent >> word)
cout << translate(word) << endl;
system("pause");
return 0;
}


最佳答案

我已经注释掉了所有不必要的部分。

#include <iostream>
// #include <cstring>
// #include <sstream>
#include <ccytpe> // You were relying on an include dependency; this is the
// library that contains isalpha()
using namespace std;

string translate(string word)
{
string morseCode[] = { ".-x", "-...x", "-.-.x", "-..x", ".x", "..-.x",
"--.x", "....x", "..x", ".---x", "-.-x", ".-..x", "--x", "-.x", "---x",
".--.x", "--.-x", ".-.x", "...x", "-x", "..-x", "...-x", ".--x", "-..-x",
"-.--x", "--..x" };
char ch;
string morseWord = " ";
//string morseWord = " " == "xx";


for (unsigned int i = 0; i < word.length(); i++)
{
if (isalpha(word[i]))
{
ch = word[i];
ch = toupper(ch);
morseWord += morseCode[ch - 'A'];
// morseWord += morseCode[ch = ' '] == "xx"; // Having a space
// character is
// impossible here
//morseWord += "xx";
//morseWord += " " == "xx";
}
else if (isspace(word[i])) // True for any whitespace character
{
morseWord += "xx";
}

}
return morseWord;
}

int main()
{
// stringstream stringsent;
string sentence;
// string word = ""; // should just be 'string word;'
// Default constructed strings are already empty

cout << "Please enter a sentence: ";
getline(cin, sentence);
// stringsent << sentence;
cout << "The morse code translation for that sentence is: " << endl;
cout << translate(sentence) << endl;
return 0;
}

您的问题有两个方面。空格字符不是字母顺序的,因此没有空格字符可以进入您的 if block 。其次,在一次只发送一个单词的情况下,您甚至从来没有发送空格字符作为开头。

以下是上述代码的示例输出:

Please enter a sentence: hello world
The morse code translation for that sentence is:
....x.x.-..x.-..x---xxx.--x---x.-.x.-..x-..x

关于c++ - 单词之间的摩尔斯电码空格问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58381647/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com