我正在創建一個地址簿程序,允許用戶通過名字,姓氏,電話號碼和地址進行搜索。系統會提示用戶輸入文件名,並將文件讀入數組中。我無法修改現有的SearchFirstName函數來遍歷數組。我已經多次閱讀過這個話題,我只是不理解它。任何幫助將不勝感激。C++數組和讀取文件
文件
Susan, Smith, 123 456 789
101 Main Street
Bob, Smith, 567 345 9076
456 Market Street
頭文件
#include<string>
using namespace std;
enum Title {Mr, Mrs, Ms, Dr, NA};
struct NameType {
Title title;
string firstName;
string lastName;
};
struct AddressType {
string street;
string city;
string state;
string zip;
};
struct PhoneType {
int areaCode;
int prefix;
int number;
};
struct entryType {
NameType name;
AddressType address;
PhoneType phone;
};
const int MAX_RECORDS = 50;
struct addressBookType {
entryType record[MAX_RECORDS];
int numEntries;
};
代碼
string bookArray[MAX_RECORDS];
int main()
{
entryType userRecord;
string filename;
ifstream inData;
char searchOption;
OpenFile(filename, inData);
MainMenu(inData, filename);
return 0;
}
void OpenFile(string& filename, ifstream& inData)
{
do {
cout << "Enter file name to open: ";
cin >> filename;
inData.open(filename.c_str());
if (!inData)
cout << "File not found!" << endl;
} while (!inData);
if(inData.is_open())
{
for(int i=0; i<MAX_RECORDS;i++)
{
inData>> bookArray[i];
}
}
}
// Searches passed file stream for a first name read from the user
void SearchFirstName(ifstream& inData)
{
string searchName;
entryType userRecord;
string normalSearchName, normalFirstName;
char choice;
bool found = false;
cout << "Enter first name to search for: ";
cin >> searchName;
normalSearchName = NormalizeString(searchName); // Convert name to all uppercase
// Loop through all records in the file
while (GetRecord(inData, userRecord)){
normalFirstName = NormalizeString(userRecord.name.firstName); // Convert retrieved string to all uppercase
if (normalFirstName == normalSearchName) { // Requested name matches
PrintRecord(userRecord);
cout << "Is this the correct entry? (Y/N)";
cin >> choice;
choice = toupper(choice);
cout << endl;
if (choice == 'Y') {
found = true;
break;
}
}
}
// Matching name was found before the end of the file
if (inData && !found){
cout << "Record found: " << endl;
PrintRecord(userRecord);
cout << endl;
}
else if (!found) // End of file. Name not found.
{
cout << searchName << " not found!" << endl << endl;
}
// Clear file fail state and return to beginning
inData.clear();
inData.seekg(0);
}
我嘗試
void SearchFirstName(ifstream& inData)
{
string searchName;
entryType userRecord;
cout << "Enter first name to search for: ";
cin >> searchName;
string newSearchName = NormalizeString(searchName);
string upFirst = NormalizeString(userRecord.name.firstName);
for (int i=0;i<MAX_RECORDS;i++)
{
while(newSearchName == upFirst)
{
if (bookArray[i]== upFirst)
{
cout<<"Name Found";
cout <<bookArray[i]; //test case
}
}
}
}
你在哪裏遇到問題? – chbchb55
@ chbchb55我編輯了我的問題以顯示我所嘗試的內容。我的代碼沒有正確循環SearchFirstName函數中的數組。 – Taylor