【发布时间】:2020-02-11 08:46:48
【问题描述】:
我无法让我的代码将空格字符转换为“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;
}
【问题讨论】:
-
我不确定我是否理解正确,您能否提供一个简短的输入和预期输出示例?只是指出错误的来源:
morseWord += morseCode[ch = ' '] == "xx";将首先将''(32 作为 int)分配给ch,然后查找morseCode[' '],这将是morseCode[32],这是未定义的行为,因为您的数组仅包含 26 个条目。然后它将这个值与const char *"xx" 进行比较,这将是错误的(例如 0)。然后它将 0 ('\0' as char) 到morseWord -
好收获。当我给出答案时,我没有注意如何评估该行,因为空格字符不可能允许进入该块。
标签: c++ string stl containers morse-code