Я пытаюсь ввести форму проверки данных, в которой, когда пользователь вводит номер ISBN книги, если он уже был сохранен, тогда он выдает сообщение об ошибке. Однако у меня возникают проблемы с этим. Я не уверен, правильно ли я перегружал оператор ==, и я не уверен, как сравнивать векторные значения в функции store_ISBN().Сравнение значений, вводимых в значения в векторе
Вот код:
#include "std_lib_facilities.h"
// Classes ---------------------------------------------------------------------
class Book{
public:
vector<Book> books; // stores book information
Book() {}; // constructor
friend ostream& operator<<(ostream& out, const Book& b);
bool operator==(const Book& d);
string what_title();
string what_author();
int what_copyright();
void store_ISBN();
void is_checkout();
private:
char check;
int ISBNfirst, ISBNsecond, ISBNthird;
char ISBNlast;
string title;
string author;
int copyright;
};
// Class Functions -------------------------------------------------------------
string Book::what_title()
{
cout << "Title: ";
getline(cin,title);
cout << endl;
return title;
}
string Book::what_author()
{
cout << "Author: ";
getline(cin,author);
cout << endl;
return author;
}
int Book::what_copyright()
{
cout << "Copyright Year: ";
cin >> copyright;
cout << endl;
return copyright;
}
void Book::store_ISBN()
{
bool test = false;
cout << "Enter ISBN number separated by spaces: ";
while(!test){
cin >> ISBNfirst >> ISBNsecond >> ISBNthird >> ISBNlast;
for(int i = 0; i < books.size(); ++i)
if(ISBNfirst == books[i]) cout << "test"; // no idea how to implement this line
if((ISBNfirst<0 || ISBNfirst>9) || (ISBNsecond<0 || ISBNsecond>9) || (ISBNthird<0 || ISBNthird>9))
error("Invalid entry.");
else if(!isdigit(ISBNlast) && !isalpha(ISBNlast))
error("Invalid entry.");
else test = true;}
cout << endl;
}
void Book::is_checkout()
{
bool test = false;
cout << "Checked out?(Y or N): ";
while(!test){
cin >> check;
if(check == 'Y') test = true;
else if(check == 'N') test = true;
else error("Invalid value.");}
cout << endl;
}
// Operator Overloading --------------------------------------------------------
bool Book::operator==(const Book& d){ // is this right???
if((ISBNfirst == d.ISBNfirst) && (ISBNsecond == d.ISBNsecond)
&& (ISBNthird == d.ISBNthird) && (ISBNlast == d.ISBNlast)) return true;
else return false;
}
ostream& operator<<(ostream& out, const Book& b){
out << "Title: " << b.title << endl;
out << "Author: " << b.author << endl;
out << "ISBN: " << b.ISBNfirst << "-" << b.ISBNsecond << "-" << b.ISBNthird << "-" << b.ISBNlast << endl;
out << endl;
return out;
}
// Main ------------------------------------------------------------------------
int main()
{
Book store;
string question;
while(true){
store.what_title();
store.what_author();
store.what_copyright();
store.store_ISBN();
store.is_checkout();
store.books.push_back(store);
cout << "Are you finished?(Y or N): ";
cin >> question;
if(question == "Y") break;
else if(question == "N"){
cout << endl;
cin.ignore();}
else error("Invalid value.");
}
cout << endl;
cout << "Books stored -\n" << endl;
for(int i = 0; i < store.books.size(); ++i)
cout << store.books[i];
keep_window_open();
}
Обратите внимание, что в функции store_ISBN я только Тестам для одной переменной, так как я не хочу, чтобы впечатать все это, прежде чем я понять, как это сделать Это.
Как вы можете видеть каждый раз, когда книга проходит через петлю в основном, данные для этой книги хранятся. Затем я могу выводить все данные после цикла, перегружая оператор < < для печати Title, Author и ISBN. Поэтому я думаю, что я должен иметь доступ к этим отдельным данным в векторе для сравнения с пользователем ISBN, но я не знаю, как это сделать. Части, которые меня путают, были прокомментированы как таковые.
Обратите внимание, что ваш цикл while является плохим; пожалуйста, используйте while (question! = "Y") вместо while (true). – jkeys
также не используют «какие» префиксы, просто используйте имя переменной. Общее соглашение диктует, что каждый элемент данных отслеживает «_» (например, string title_;), а затем используйте имя без подчеркивания для доступа к этой переменной. – jkeys