嗨,我对c ++编程很陌生,所以请耐心等待。我有一个库txt文件,其中包含14本书及其作者。我正在尝试将此库加载到数组中,然后接受用户输入,以便按标题或作者姓名搜索库。到目前为止,这是我的代码......
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
using namespace std;
const int ARRAY_SIZE = 1000;
string bookTitle [ARRAY_SIZE];
string bookAuthor [ARRAY_SIZE];
int loadData(string pathname);
void showAll(int count);
int showBooksByAuthor (int count, string name);
int showBooksByTitle (int count, string title);
int main ()
{
int numFound, nextNumFound, number, numOfBooks;
char reply;
string bookTitles[5], authorName[5], backupFile;
cout << "Welcome to Brigham's library database." << endl;
cout << "Please enter the name of the backup file:";
cin >> backupFile;
numOfBooks = loadData (backupFile);
if (numOfBooks == -1) {
cout << endl;
} else {
cout << numOfBooks << " books loaded successfully." << endl;
}
do {
cout << "Enter Q to (Q)uit, Search (A)uthor, Search (T)itle, (S)how All: ";
cin >> reply;
switch (reply) {
case 'a':
case 'A':
cout << "Author's name: ";
cin.getline(authorName, 5);
numFound = showBooksByAuthor(numOfBooks, authorName);
cout << numFound << " records found.";
cout << endl;
break;
case 'q':
case 'Q':
cout << endl;
break;
case 's':
case 'S':
showAll(numOfBooks);
cout << endl;
break;
case 't':
case 'T':
cout << "Book title: ";
getline(cin, bookTitles);
numFound = showBooksByTitle(numOfBooks, bookTitles);
cout << nextNumFound << " records found.";
cout << endl;
break;
default:
cout << "Invalid input" << endl;
break;
}
} while (reply != 'q' && reply != 'Q');
}
int loadData (string pathname){
int count = 0, noCount = -1;
ifstream inputFile;
string line, reply;
inputFile.open(pathname.c_str());
if (!inputFile.is_open()) { //If the file does not open then print error message
cout << "Unable to open input file." << endl;
return noCount;
}
for (int i = 1; i < ARRAY_SIZE; i++) {
getline(inputFile, bookTitle[i]);
getline(inputFile, bookAuthor[i]);
//cout << bookTitle[i] << endl;
//cout << bookAuthor[i] << endl;
count++;
if(inputFile.eof()) {
return count;
}
}
}
void showAll (int count) {
for (int j = 1; j <= count; j++) {
cout << bookTitle[j] << endl;
cout << bookAuthor[j] << endl;
}
}
int showBooksByAuthor (int count, string name) {
int numByAuthor;
for (int k = 1; k <= count; k++) {
if(name == bookAuthor[k]) {
cout << bookTitle[k] << " (" << bookAuthor[k] << ")" << endl;
numByAuthor++;
}
}
return numByAuthor;
}
int showBooksByTitle (int count, string title) {
int numByTitle;
for (int i = 1; i <= count; i++) {
if (title == bookTitle[i]) {
cout << bookTitle[i] << " (" << bookAuthor[i] << ")" << endl;
numByTitle++;
}
}
return numByTitle;
}
所以我的问题是我的int showBooksByAuthor
和int showBooksByTitle
函数。目前,当用户输入't'
或'a'
按标题或作者查找书籍时,它甚至不会提示他们输入标题或作者,它只会自动吐出0条记录。在我将switch语句中的案例't'
和案例'a'
从getline(cin, stringname)
更改为cin >> stringname
后,就会出现此错误。我意识到,如果他们要输入大于1个字的任何输入,那么函数将失败,因为我知道cin
读取第一个空格。但我不明白为什么getline
功能不起作用。我代码中的任何想法?抱歉,如果格式错误。