我目前正在开发一个库程序,特别是从文本文件中删除一本书。这是有问题的功能:
void deleteBook(){
ifstream fin;
ofstream fout;
int fileLength = 0;
bool bookExist, looper = false, looper2 = false;
string isbn, author, title, checkOutDate, dueDate, answer, fileLine, isbnCurrent;
while (looper == false){ //Loop to ensure user inputs a valid book
cout << endl << "Enter the Isbn of the book you would like to delete: "; //isbn determines book
cin >> isbn;
bookExist = isBookExist(isbn);
if (bookExist == true){
looper = true;
}
else{
cout << endl << "The book you have entered does not exist in the system, please try again" << endl;
}
}
getBookInfo(isbn, author, title, checkOutDate, dueDate); //Retrieves data about book and displays
cout << endl << "The isbn of the book is: " << isbn;
cout << endl << "The author of the book is: " << author;
cout << endl << "The title of the book is: " << title;
cout << endl << "The check out date of the book is: " << checkOutDate;
cout << endl << "The due date of the book is: " << dueDate;
while (true){
cout << endl << "Are you sure you would like to delete this book? (Enter 'yes' or 'no'): ";
cin >> answer;
if (cin.fail()){ //This most likely wont come up under any circumstances, but is here for completion
cout << "Your answer was not valid, please try again." << endl;
}
if ((answer.compare("yes") == 0) || (answer.compare("Yes") == 0)){
fin.open(booksFile); //open books file and a temporary
fout.open("tempBook.txt");
while (getline(fin, fileLine)) //Check how long file is
fileLength++;
fin.close(); //reset book file
fin.open(booksFile);
while (looper2 == false){
for (int i = 0; i < fileLength; i += 5){
getline(fin, isbnCurrent); //Go through file and look for book in question
if (isbn == isbnCurrent){
fout << " " << endl << " " << endl << " " << endl << " " << endl << " ";
looper = true; //If book is found, set all fields to empty
break;
}
getline(fin, author); //If not, continue through file
getline(fin, title);
getline(fin, checkOutDate);
getline(fin, dueDate);
fout << isbn << endl << title << endl << author << endl << checkOutDate << endl << dueDate << endl;
//Outputs data back onto file
}
fin.close();
fout.close();
remove("books.txt"); //sets book file to the temp
rename("tempBook.txt", "books.txt");
}
} else if ((answer.compare("no") == 0) || (answer.compare("No") == 0)){
break; //Leave function if user decides not to delete
}
else
cout << "Input invalid, please enter either 'yes' or 'no' " << endl;
}
}
该程序似乎一直工作到yes / no部分。此时输入没有按预期工作,但输入yes无效,程序只是静止不动。我不完全确定问题出在哪里,尽管booksFile的格式如下:
ISBN 标题 作者 入住日期 退房日期
提前致谢!
答案 0 :(得分:1)
在你的内在while循环中你有:
while (looper2 == false) { ... }
但是,在该循环中,您没有将lopper2
设置为true
(您将lopper
设置为true
。)
顺便说一句:考虑一下whiles
的使用方式,您是否考虑过使用break
代替looper
变量?例如,第一种情况就像这样清洁:
while (true)
{
cout << endl << "Enter the Isbn of the book you would like to delete: ";determines book
cin >> isbn;
if (isBookExist(isbn))
break;
cout << endl << "The book you have entered does not exist in the system, please try again" << endl;
}