我正在使用電話簿,並且迄今已成功地能夠讓用戶輸入他們的信息,將其保存爲字符串,將字符串保存到文件並搜索該字符串使用關鍵字。但是,它只對輸入的第一個聯繫人有效。輸入新聯繫人時,它會覆蓋保存在文件中的前一個字符串。我怎樣才能讓它打印到下一行,並開發可以通過搜索的聯繫人列表。任何幫助深表感謝。這裏是我的代碼:將多個字符串打印到文件
#include <iostream>
#include <string>
#include <ostream>
#include <fstream>
using namespace std;
struct person
{
string Name;
string Address;
string PhoneNumber;
string Email;
};
int main()
{
ResetUserSelection:
vector<person>ContactList;
int userselection = 0;
cout << "Press 1 to Add Contact" << endl;
cout << "Press 2 to Search for Contact"<<endl;
cout << "What do you want to do? ";
cin >> userselection;
if(userselection == 1)
{
person newPerson;
cout << endl;
cin.ignore();
cout << "What is your Name? " ;
getline(cin,newPerson.Name);
cout << "What is your Address? " ;
getline(cin,newPerson.Address);
cout << "What is your Phone Number? " ;
getline(cin,newPerson.PhoneNumber);
cout << "What is your Email? ";
getline(cin,newPerson.Email);
cout << endl;
string fullContact = "Name: " + newPerson.Name + ", Address: " + newPerson.Address + ", Phone Number: " + newPerson.PhoneNumber + ", Email: " + newPerson.Email + "\n";
cout <<fullContact;
cout << endl;
ofstream myfile;
myfile.open ("contactlist.txt");
myfile << fullContact;
myfile.close();
goto ResetUserSelection;
goto ResetUserSelection;
}
else
{
string search;
ifstream Myfile;
Myfile.open ("contactlist.txt");
cout << "Who do you want to search for?" << endl;
cin >> search;
cout << endl;
ifstream myfile;
myfile.open ("contactlist.txt");
string contact;
while(getline(myfile, contact))
{
if(contact.find(search) != string::npos)
{
cout << search << "'s contact info" << endl << contact << endl << endl;
}
}
myfile.close();
goto ResetUserSelection;
}
}
這就是爲什麼人們討厭'goto',因爲有些人給它最壞的可能使用,你不能寫一個循環嗎? –