c++ - 在二叉树中使用 strtok 解码摩尔斯电码 - 垃圾输出

标签 c++ string binary-tree strtok morse-code

我能够将英语编码为摩尔斯电码,但我在进行反向操作时遇到了问题。这是我到目前为止所拥有的:

在 main() 中:

cout << "Enter your Morse code, separated by /, ended by *: ";
cin.getline(morseCode, 100, '*');
char* token = strtok(morseCode, "/");
while(token != NULL)
{
    cout << endl << "Decoding: " << token << endl;
    string newCode = token;
    t.Decode(newCode);
    token = strtok(NULL, "/");
}

解码函数:

void Decode(string x)
{
    Node* r = SearchAndReturnString(root, x);
    if(r->code == x) cout << r->letter;
    else cout << r->code << " with x being " << x << endl; cout << "Error.";
}

我的输出是一堆随机垃圾数据然后程序崩溃了。我知道它与 SearchAndReturnString 函数有关,但我不知道它还能做什么。


编辑:

节点结构:

struct Node
{
    string letter;
    string code;
    Node *left;
    Node *right;
};

SearchAndReturn 函数:

Node* SearchAndReturnString(Node *r, string x)
{
    if(r != NULL)
    {
        if(r->code == x) {cout << r->code << " matches " << x << endl; return r;}
        else if(r->code > x) {SearchAndReturnString(r->left, x);}
        else {SearchAndReturnString(r->right, x);}
    }
    else return NULL;
}

这里是请求的完整代码:

标题:http://pastebin.com/QyaakvMK

主要:http://pastebin.com/NcseqrbX

最佳答案

问题似乎是,当您将 std::string 传递给 tree.Decode 时,它会调用 SearchAndReturn具有与单个 char 相同的变量。您的问题未包含 Minimal, Complete and Verifiable example所以很难知道哪个是正确的,但至少有一个是错误的。

关于c++ - 在二叉树中使用 strtok 解码摩尔斯电码 - 垃圾输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23419077/

相关文章:

c++ - 从服务器向客户端发送数据

C++ 使用 while 循环检查输入值

java - 如何从java中的字符串中提取子字符串

java - 有什么方法可以分析传递给 String.format(...) 的模式

c++ - 我如何在阅读时 "unzip"gzip 流

c++ - 如何 enable_if 具有可变模板参数的类?

python - 无法用\r 替换打印的行

c++ - 删除有两个 child 的目标

java - 打印哈夫曼树中的正确路径

java - Java 中泛型类型的树实现