我能够将英语编码为摩尔斯电码,但我在进行反向操作时遇到了问题。这是我到目前为止所拥有的:
在 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;
}
这里是请求的完整代码:
最佳答案
问题似乎是,当您将 std::string
传递给 tree.Decode
时,它会调用 SearchAndReturn
具有与单个 char
相同的变量。您的问题未包含 Minimal, Complete and Verifiable example所以很难知道哪个是正确的,但至少有一个是错误的。
关于c++ - 在二叉树中使用 strtok 解码摩尔斯电码 - 垃圾输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23419077/