Try something more like this:
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
cout<<"An empty string or EOF will stop the program"<<endl;
for ( ; ; ) {
string name;
cout<<"Enter a name to search for: ";
if ( !getline ( cin, name ) || name.empty() )
break;
ifstream phonebook ( "phone.dat" );
if ( !phonebook ) {
cerr<<"Error opening file"<<endl;
return EXIT_FAILURE;
}
vector<string> lines;
string line;
while ( getline ( phonebook, line ) ) {
if ( line.find ( name ) )
lines.push_back ( line );
}
if ( lines.empty() )
cout<<"No records found"<<endl;
else if ( lines.size() == 1 )
cout<<"One record found"<<endl;
else
cout<<"Multiple records found"<<endl;
for ( vector<string>::size_type i = 0; i < lines.size(); i++ )
cout<< lines[i] <<endl;
}
return EXIT_SUCCESS;
}
This way you can not only search by first name, last name, or both, multiple occurances of the name entered will be listed, rather than just the first one found.
Notice how I used getline to read an entire line and then process it in memory. In the end, that's the easiest way to write robust and error free I/O, and the primary lesson you'll get from the code I showed you.
Reputation Points: 6442
Solved Threads: 1393
Bad Cop
Offline 11,807 posts
since Sep 2004