Проблема с пробелами азбуки Морзе между словами

У меня возникли проблемы с попыткой заставить мой код преобразовать символ пробела в «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;
}



person Matthew Mills    schedule 14.10.2019    source источник
comment
Я не уверен, правильно ли я вас понял, не могли бы вы привести краткий пример ввода и ожидаемого результата, пожалуйста? Просто чтобы указать на источник ошибок: 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
comment
Хороший улов. Когда я давал свой ответ, я не обратил внимания на то, как оценивается эта строка, поскольку символ пробела не может разрешить вход в этот блок.   -  person sweenish    schedule 14.10.2019


Ответы (1)


Я закомментировал все ненужные биты.

#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. Во-вторых, отправляя только одно слово за раз, вы никогда не отправляли даже пробелы.

Вот пример вывода кода выше:

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