There are so many approaches. Here something that works. Perhaps you could fine more ways.
Code:
#include <iostream>
#include <string>
#include <climits>
#include <fstream>
using std::cin;
using std::cout;
using std::endl;
using std::numeric_limits;
using std::streamsize;
using std::string;
using std::ifstream;
//Optional function: depends on IDE. Remove if not needed. void wait_for_enter();
//Additional helper. Remove if not needed. void reset_istream();
int main(int argc, char *argv[])
{
ifstream theAccount("account.lst");
if(!theAccount)
{
cout<<"ERROR! Reason: could not open or find file."<<endl;
wait_for_enter();
return -1;
}
cout<<"employee number: ";
unsigned employeeNumber;
cin>>employeeNumber;
unsigned empNum;
string employeeName;
double payRate;
bool b_found(false);
// Assuming *.lst has this format (note \t): unsigned\tstring\tdouble while(theAccount>>empNum)
{
if(empNum == employeeNumber)
{
b_found = true;
theAccount >> employeeName >> payRate;
cout<<empNum<<endl;
cout<<employeeName<<endl;
cout<<payRate<<endl;
break;
}
else
{
theAccount.ignore( numeric_limits<streamsize>::max(), '\n' );
}
}
//Eof not reached but item not found either. So something must have gone wrong. if( !theAccount.eof() && b_found == false)
{
cout<<"ERROR! Reason: could not process the file properly."<<endl;
cout<<"Terminating program..."<<endl;
theAccount.close();
wait_for_enter();
return -1;
}
else if( b_found == false ) //All went O.K. but item has not been found.
{
cout<<"This employee number does not exist."<<endl;
}
theAccount.close();
reset_istream();
wait_for_enter();
return 0;
}
//--------------------------------------------------- void reset_istream()
{
if(cin.eof())
{
cin.clear();
}
else
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
}
//--------------------------------------------------- void wait_for_enter()
{
cout << "press <enter> to continue...";
// Reset failstate, just in case.
cin.clear();
string line;
getline( cin, line);
}