#include<iostream>
#include<fstream>
#include<ostream>
usingnamespace std;
int main()
{
//creates input file stream
ifstream inFile;
//opens input file "Intermediate24.txt"
inFile.open("Intermediate24.txt",ios::in);
//payroll code / sentinel value
int payrollCode = 0;
int payroll = 0;
int pay = 0;
do
{
cout<<endl<<"Enter an Integer as Payroll Code (-1 to exit): ";
cin>>payrollCode;
if(payrollCode != -1)
{
//takes first character of file
inFile>>payroll;
//compares obtained integer to payrollCode
if(payroll == payrollCode)
{
//ignores 1 character
inFile.ignore(1);
//takes pay
inFile>>pay;
}
else
{
//attempting to ignore whole line
inFile.ignore('\n');
//take number form next line
inFile>>payroll;
}
//displays payroll code and pay from text file
cout<<endl<<"Payroll Code: "<<payroll<<" Pay: "<<pay;
}
}
while(payrollCode != -1);
//closes input file
inFile.close();
system("pause");
return(0);
}
The code is capable of reading the whole first line and transcribing the data ,but after that I get skewed results, often with the pay as the next payroll code and it displaying the wrong pay.
To fix this i had to gut the program and start over "almost".
moved inFile.open("out.txt",ios::in); to the first line inside the loop.
put in a chk to see if the file was open if(inFile.is_open())
put in another check to make sure the value was valid if ((payrollCode >= 1) && (payrollCode <= 32))
By far the biggest change is how you read in the file
I created a while loop and read in the line
1 2 3 4 5 6 7
while (payroll != payrollCode)
{
//Reads first line of file
inFile>>payroll;
inFile.ignore(1);
inFile>>pay;
}// end while
Once the program found the right value, I closed the file, and since I moved the open file inside the do loop, if it doesn't exit, it will open the file again.