对于我的CS课程,我们已经获得了使用此处的文本文件创建英语到西班牙语翻译的作业:http://www.ilovelanguages.com/IDP/files/Spanish.txt
到目前为止,我已经插入了插件,但是当我运行程序时 - 单词混杂在一起,我打赌txt文件每行有多个单词的事实是什么破坏了它
#include<iostream>
#include<string>
#include<fstream>
using namespace std;
class transl
{ private:
class word
{ public:
string eng_word,
spa_word;
word * next,
* prev;
word(string engl_word, string span_word, word * next1 = NULL, word * prev1 = NULL)
{ eng_word = engl_word;
spa_word = span_word;
next = next1;
prev = prev1; }
};
word * head,
* tail;
public:
transl::transl()
{ head = NULL;
tail = NULL; }
transl::~transl()
{ word * wordPtr, * nextWord;
wordPtr = head;
if(head == NULL)
return;
while(wordPtr != NULL)
{ nextWord = wordPtr->next;
delete wordPtr;
wordPtr = nextWord; }
}
void insert(string engl_word, string span_word)
{ if(head == NULL)
head = new word(engl_word, span_word);
else
{ word * wordPtr;
wordPtr = head;
while(wordPtr->next != NULL)
{ wordPtr->next->prev = wordPtr;
wordPtr = wordPtr->next; }
wordPtr->next = new word(engl_word, span_word);
cout << wordPtr->next->eng_word << " " << wordPtr->next->spa_word << endl; }
}
string search(string engl_word)
{ return "Hello"; }
};
int main()
{ ifstream inFile; inFile.open("dictionary.txt");
string engl_word, span_word;
transl test;
if (!inFile)
{ cout << "ERROR! CANNOT LOCATE DICTIONARY!" << endl;
system("pause");
return 1; }
cout << "Loading Dictionary: ";
while(inFile >> engl_word >> span_word)
{ test.insert(engl_word, span_word); }
cout << "Done!" << endl;
system("pause");
system("CLS");
cout << "Translate: ";
cin >> engl_word;
cout << "The translation of " << engl_word << " is " << test.search(engl_word) << '.' << endl;
system("pause");
return 0; }
它的外观如下:
peor wound
la herida
wounded herida
Done!
Press any key to continue . . .
有人知道正确插入值的程序
答案 0 :(得分:2)
wordPtr->next->prev = wordPtr;
是多余的,令人困惑。您正在搜索列表的末尾,但在此过程中对其进行修改。
您忘记在插入中编写新单词的prev指针。
然而,真正的问题在于阅读字典。当您执行inFile >> engl_word >> span_word
时,会读入两个空白限制列表。但是,西班牙语条目不受空格限制,但占用了其余部分。虽然您可以使用>>
阅读英文单词,但您需要getline( cin, span_word )
之类的内容来解析西班牙语表达。