为什么这会导致Mac无限循环?
我写了下面的函数来读取文件,并将“记录”加载到Visual Studio 2015中的BST中。它的工作方式与我在Windows中预期的一样,但是当我在mac上运行该函数时,会导致无限大循环。我无法弄清楚为什么。有人可以阐明它。有完整的代码更新了,问题是用下面的函数:为什么这会导致Mac无限循环?
BinarySearchTree readFile()
{
ifstream myfile;
myfile.open("character.txt");
string name;
string aString = "Empty";
BinarySearchTree loadTree;
List list1;
int index = 1;
bool finishRecord = false;
if (!myfile.peek() == myfile.eof())
{
while (!myfile.eof())
{
getline(myfile, name);
while (!finishRecord)
{
getline(myfile, aString);
if (aString == "/")
{
finishRecord = true;
}
else
{
list1.insert(index, aString);
index += 1;
}
}
KeyedItem an_item(name, list1, true);
loadTree.searchTreeInsert(an_item);
//reset variables used for each record
index = 1;
list1.removeAll();
finishRecord = false;
}
}
myfile.close();
return loadTree;
} // end readFile
全码:
#include <iostream> //needed for input and output and the console screen
#include <fstream> //needed to read/write a file
#include <iomanip>
#include <algorithm> //needed to use the transform function
#include "ListP.h" //linked list class
#include "BST.h" // binary tree operations
using namespace std;
string suspectsArray[256]; //array of the suspects
int suspectIndex = 0;
KeyedItem ADD();
BinarySearchTree readFile();
void QUIT(BinarySearchTree& passedTree, string addedItems[], int arrayIndex);
bool withinTree(BinarySearchTree& passedTree, string name);
string INQUIRY(BinarySearchTree& passedTree);
void suspects(TreeItemType& anItem);
void findTip(BinarySearchTree& passedTree, string tip, int &noSuspects);
int main()
{
string aString;
BinarySearchTree characterTree = readFile();
KeyedItem an_Item;
string addedItems[256] = {};
int index = 0;
string answer;
string inquiryReturn = "";
bool main = false;
bool inTree = false;
while (!main)
{
cout << "WE ARE AT MAIN LOOP. YOU CAN ADD, INQUIRY, OR QUIT";
cout << endl;
if (inquiryReturn == "")
{
cin >> answer;
cin.ignore(); //need to flush the input for the getline()
}
else
{
inquiryReturn = "";
}
//since we need to accept the input regardless of it case
//so going to make the input into lower case
transform(answer.begin(), answer.end(), answer.begin(), tolower);
//determine which operation the user called
if (answer == "add") //user wishes to ADD a character
{
cout << endl;
an_Item = ADD();
//need to determine if the record for the character
//is already in the tree or not
inTree = withinTree(characterTree, an_Item.getKey());
if (!inTree)
{
addedItems[index] = an_Item.getKey();
index += 1;
characterTree.searchTreeInsert(an_Item);
}
else
{
cout << "Character already in tree." << endl;
}
inTree = false;
}
else if (answer == "inquiry") //user wishes to do an INQUIRY
{
cout << "User wants to do an INQUIRY" << endl;
characterTree.postorderTraverse(suspects);
inquiryReturn = INQUIRY(characterTree);
answer = inquiryReturn;
suspectIndex = 0;
}
else if (answer == "quit") //user wishes to QUIT the program
{
if (index > 0) //if the user added a character, save
{
cout << "OK, saving database to file "
"\"character.txt\" ";
QUIT(characterTree, addedItems, index);
cout << "... Done. Goodbye." << endl;
main = true;
}
else
{
cout << "OK, saving database to file "
"\"character.txt\" ";
cout << "... Done. Goodbye." << endl;
main = true;
}
}
else
{
cout << "You didn't enter a valid command." << endl;
}
}
return 0;
} //end main
void suspects(TreeItemType& anItem)
{
suspectsArray[suspectIndex] = anItem.getKey();
suspectIndex++;
}
//Function to get a record to add to the binary search tree
//gets the record in the type KeyedItem
KeyedItem ADD()
{
string name;
string a_string;
List list1;
int index = 1;
bool end = false;
cout << "OK, we are now adding a character to the database."
<< endl;
cout << "Name of Character:" << setw(5) << " ";
getline(cin, name);
cout << "Attributes:" << setw(12) << " ";
//loop to get attributes if any
while (!end)
{
getline(cin, a_string);
if (a_string == "")
{
//if no attributes were added, need to prompt for one
if (list1.getLength() == 0)
{
cout << "Need to enter at least one attribute." <<
endl << setw(23) << " ";
}
else
{
cout << endl;
end = true;
}
}
else
{
list1.insert(index, a_string);
index += 1;
cout << setw(23) << " ";
}
}
KeyedItem an_item1(name, list1, true);
return an_item1;
} // end ADD
//Function to read the database file and
//load all of the records into a Binary Search Tree.
BinarySearchTree readFile()
{
ifstream myfile;
myfile.open("character.txt");
string name;
string aString = "Empty";
BinarySearchTree loadTree;
List list1;
int index = 1;
bool finishRecord = false;
if (!myfile.peek() == myfile.eof())
{
while (!myfile.eof())
{
getline(myfile, name);
while (!finishRecord)
{
getline(myfile, aString);
if (aString == "/")
{
finishRecord = true;
}
else
{
list1.insert(index, aString);
index += 1;
}
}
KeyedItem an_item(name, list1, true);
loadTree.searchTreeInsert(an_item);
//reset variables used for each record
index = 1;
list1.removeAll();
finishRecord = false;
}
}
myfile.close();
return loadTree;
} // end readFile
//Function to run if additional shady characters were manually added to the Binary Search Tree
//It should the added characters to the database text file.
void QUIT(BinarySearchTree& passedTree, string addedItems[], int arrayIndex)
{
ofstream outfile; //variable that will be assigned to the file
KeyedItem an_item; //record that needs to be added to file
string aString;
outfile.open("character.txt", ios::app);
if (outfile.is_open())
{
for (int i = 0; i < arrayIndex; i++)
{
passedTree.searchTreeRetrieve(addedItems[i], an_item);
outfile << an_item.getKey() << "\n";
int jkl = an_item.attributes.getLength();
for (int bnm = 1; bnm < jkl + 1; bnm++)
{
an_item.attributes.retrieve(bnm, aString);
outfile << aString << "\n";
}
outfile << "/\n";
}
outfile.close();
}
} // end QUIT
//function to check whether or not the character is already in the tree
bool withinTree(BinarySearchTree& passedTree, string name)
{
KeyedItem item;
try
{
passedTree.searchTreeRetrieve(name, item);
}
catch (TreeException& error)
{
//the character is not within the tree
return false;
}
//the character is within the tree
return true;
} // end withinTree
//Function to if the tip matches any of the attributes of the suspects
void findTip(BinarySearchTree& passedTree, string tip,int &noSuspects)
{
KeyedItem aItem;
bool tipFound = false;
string aString;
//look at each of the characters attributes
//to see if they are a match for the tip
for (int asd = 0; asd < suspectIndex; asd++)
{
tipFound = false;
if (suspectsArray[asd] != "")
{
passedTree.searchTreeRetrieve(suspectsArray[asd], aItem);
//goes through each of the attributes of a character
for (int iop = 1; iop < aItem.attributes.getLength() + 1; iop++)
{
aItem.attributes.retrieve(iop, aString);
transform(aString.begin(), aString.end(), aString.begin(), toupper);
if (aString == tip)
{
tipFound = true;
}
}
//if none of character's attribute match
//remove them from the suspectArray
if (tipFound == false)
{
suspectsArray[asd] = "";
noSuspects -= 1;
}
}
}
} // end findTIP
//Function to find the perpetrator, if any
string INQUIRY(BinarySearchTree& passedTree)
{
string codeName; //string variable for inquiry code name
string command; //string variable for command input
string aString;
string checkSuspect;
int noSuspects = suspectIndex;
bool tipFound = false;
cout << "OK, we are now conducting an inquiry." << endl;
cout << endl << "Enter a Code Name for this Inquiry:";
cout << setw(5) << " ";
getline(cin, codeName);
while (command != "ADD" && command != "QUIT" && command != "INQUIRY")
{
cout << "What would you like to do?" << endl;
getline(cin, command);
transform(command.begin(), command.end(), command.begin(), toupper);
if (command == "TIP")
{
cout << "Enter Tip Info:" << setw(25) << " ";
getline(cin, command);
transform(command.begin(), command.end(), command.begin(), toupper);
findTip(passedTree, command, noSuspects);
//if there's only 1 suspect left, alert the user
if (noSuspects == 1)
{
cout << "ALERT! That leaves only one \n"
<< "suspect in the " << codeName << " inquiry:"
<< setw(13) << " ";
for (int k = 0; k < suspectIndex; k++)
{
if (suspectsArray[k] != "")
{
cout << suspectsArray[k] << endl;
}
}
}
else if (noSuspects == 0) //all suspects have been eliminated
{
cout << "There no suspects that are match." << endl;
}
}
else if (command == "CHECK")
{
bool found = false;
cout << "Enter Name of character:" << setw(16) << " ";
getline(cin, checkSuspect);
transform(checkSuspect.begin(), checkSuspect.end(),
checkSuspect.begin(), toupper);
for (int p = 0; p < suspectIndex; p++)
{
aString = suspectsArray[p];
transform(aString.begin(), aString.end(), aString.begin(), toupper);
if (aString == checkSuspect)
{
cout << aString << " is a suspect." << endl;
found = true;
}
}
if (!found)
{
cout << checkSuspect << " is not a suspect." << endl;
}
}
else if (command == "PRINT")
{
cout << "Current Suspects are:" << endl;
for (int k = 0; k < suspectIndex; k++)
{
if (suspectsArray[k] != "")
{
cout << suspectsArray[k] << endl;
}
}
}
else if (command == "ADD" || command == "QUIT" || command == "INQUIRY")
{
return command;
}
}
} // end INQUIRY
使用Visual Studio编译而不是Mac编译的原因是,你越来越不走运了。你有一个错误,它使看起来就像它在Windows上工作,但Mac更幸运并且失败。
从readFile
函数开始,因为如果程序无法正确读取文件,没有必要测试程序的其余部分。垃圾在==垃圾出来。
if (!myfile.peek() == myfile.eof())
分解为int两个块,然后比较其结果。
!myfile.peek()
返回所有错误的读字符或EOF。然后不是。除非从文件读取NULL,否则这将导致false。
myfile.eof()
如果peek碰到文件的末尾,将始终返回true,否则为false。
所以空文件的情况下比较真假应该是不是输入if的正文。不知道你如何在这里获得无限循环。
至于
while (!myfile.eof())
读Why is iostream::eof inside a loop condition considered wrong?
getline(myfile, name)
返回到输入流和所述输入流的引用具有常规operator bool()
如果流是可读,则返回true,所以
while (getline(myfile, name))
实际上是你所需要的。如果由于任何原因无法读取文件,包括EOF,繁荣!该计划在这里失控。
这意味着所有的输入都可以被简化为:
while (getline(myfile, name))
{ // loop until read fails
string aString;
while (getline(myfile, aString) && aString != "/")
{ // loop until read fails or find end of record
list1.insert(index, aString);
index += 1;
}
KeyedItem an_item(name, list1, true);
loadTree.searchTreeInsert(an_item);
//reset variables used for each record
index = 1;
list1.removeAll();
}
虽然之前用于分别捕集aString != "/"
所以程序能够处理的文件结束(或者以其他方式变得不可读),以用一种强韧的情况下当前记录结束。上面的代码只是包装起来,每天都会调用它,好像没有任何问题。
while (getline(myfile, name))
{ // loop until read fails
string aString;
while (getline(myfile, aString) && aString != "/")
{ // loop until read fails or find end of record
list1.insert(index, aString);
index += 1;
}
if (!myfile)
{
// handle error
}
KeyedItem an_item(name, list1, true);
loadTree.searchTreeInsert(an_item);
//reset variables used for each record
index = 1;
list1.removeAll();
}
填补了这个空白。
此外,利用Visual Studio的调试器来逐步查看代码,并查看出现问题的位置。它会为你节省吨时间。
我们没有节点或树的代码,所以我们无法提供更多帮助。但是,一旦你知道你有数据并知道它是正确的(再次使用调试器来窥视你的节点和树来确保一切正确),你就可以完成或有条件地提出一个新的,多更具体的问题。
我的猜测是,你的程序没有找到一个“/”,其中,预计在输入流,因此从不设置finishRecord = true;
。您可能应该检查内部循环以及外部循环中的eof。
我注意到的另一件事是,如果文件不包含任何内容,它仍然会进入无限循环,即使第一个if语句应该阻止while循环在文件中没有任何内容时运行。这种行为只存在于我运行代码的mac上,而不是在我的Windows上。 –
可能是我错过了什么,从Visual Studio编译器转到g ++编译器? –
@HavikIV如果陈述不检查你认为它检查。 istream :: peek(http://www.cplusplus.com/reference/istream/istream/peek/)返回流中的下一个字符。如果流为空,则返回EOF值。 ios :: eof(http://www.cplusplus.com/reference/ios/ios/eof/)检查是否设置了eofbit标志,如果是,则返回true。正确的方式来检查流是不是空的(以你想要的方式,例如通过偷看)在这里描述:http://www.cplusplus.com/reference/string/char_traits/eof/ –
你能发布一个*完整的*例子吗?例如,这里缺少重要的东西,比如你的'#include'和''''''。 –
添加完整的代码。 –