У меня возникли проблемы с попыткой заставить мой код преобразовать символ пробела в «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" как char) доmorseWord
- person churill   schedule 14.10.2019