I am trying to write a phonebook program that uses a dat file to store the numbers (ex. in dat file--John Doe 5554445555). I have it to the point when the user keys "John" in, it will display the number. If the user keys in "John Doe", it will not work. I am entry level programming so the pointer will not move back to the top of the file unless the program is closed and restarted (which is fine for this assignment). I just need to to work with keying in John Doe....Please help if you can (Be sure to create a phone.dat file to run properly)! Thanks!

  // Open file
  ifstream phonebook;
  string nameToLookUp;
  string firstName;
  string lastName;
  string phoneNumber;
  char   runAgain;


  runAgain = 'y';
    if ( !phonebook )      { //If input doesn't open...
      cout << "Can't open the phonebook file." << endl;
      return 1;            //terminate the program

  while (runAgain=='y'||runAgain=='Y') {
    cout<<"What Name to look up? ";
    cin >> nameToLookUp; 
    while (firstName!=nameToLookUp&&lastName!=nameToLookUp&&!phonebook.eof()) { 
          phonebook >> firstName >> lastName >> phoneNumber;

    if (!phonebook.eof())
        cout << phoneNumber << endl;
        cout << "Could not find the phone number" << endl;
    cout << "Run again? ";
    cin >> runAgain;

  return (0);  

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() )

    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;
      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.

This article has been dead for over six months. Start a new discussion instead.