我正在制作电话簿,并且到目前为止已经成功地让用户输入他们的信息,将其保存为字符串,将字符串保存到文件,并使用关键字搜索该字符串。但是,它仅对输入的第一个接触有效。输入新联系人时,它会覆盖保存在文件中的上一个字符串。如何将其打印到下一行,并开发可以搜索的联系人列表。任何帮助深表感谢。这是我的代码:
#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;
}
}
答案 0 :(得分:1)
这一行:@Path
缺少第二个参数,模式,应为myfile.open ("contactlist.txt");
app
表示打开追加。 I.E.添加到文件的末尾。
答案 1 :(得分:1)
当您打开文件进行写入时,默认情况下将filepointer
设置为文件的开头。您应该在打开文件时添加附加选项。
请参阅ofstream::open的API如何执行此操作:
myfile.open ("contactlist.txt", ofstream::out | ofstream::app);
答案 2 :(得分:0)
首先,包括矢量,因为你正在使用它。 现在,你面临这个问题,因为没有给std :: fstream :: open提供正确的参数,所以它会覆盖以前的内容。
替换
myfile.open ("contactlist.txt");
带
myfile.open ("contactlist.txt",std::fstream::out|std::fstream::app);
它应该有效。有关详细信息,请http://www.cplusplus.com/reference/fstream/fstream/open/