Reading Specific Data From txt file

I'm having a little trouble getting my program to read specific data from a text file.
This is the data in the text file.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
1#27200
2#15000
3#23000
4#12000
5#25500
6#18400
7#19500
8#32000
9#29000
10#16500
20#65000
21#65500
22#70200
23#71000
24#71100
25#72000
30#83000
31#84000
32#90000 


This is my code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include<iostream>
#include<fstream>
#include<ostream>
using namespace 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.

Any help is appreciated.
Last edited on
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.

Topic archived. No new replies allowed.