IFSTREAM, very basic.

Hi. I am having trouble writing a very basic program. I am using ifstream to read information from a txt file but it is only reading the last line over and over.

Here is the important part of 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
ifstream take ("Register.txt");
	ofstream put1 ("Register.txt");
	ofstream put2 ("Charges.txt");

	int comps, reg, totalReg=0;
	float totalCharge=0, avgCharge;
	int n, c;

	cout<<"Enter the number of companies: ";
	cin>>comps;
	cout<<"\n";
	

	for (n=1;n<=comps;n++)
	{
		cout<<"Enter the number of registrants for company #"<<n<<": ";
		cin>>reg;
		put1<<reg<<"\n";
	}


	for (c=1;c<=comps;c++)
	{
		take>>reg;
		totalReg+=reg;

		if (reg<=3)
		{
			totalCharge=reg*150.0;
		}

		else if (reg>=4 && reg<=9)
		{
			totalCharge=reg*100.0;
		}

		else if (reg>=10)
		{
			totalCharge=reg*90.0;
		}

		put2<<"Company #"<<c<<" has "<<reg<<" registrant(s) and owes: $"<<totalCharge<<endl;
	}
So the problem is: my ifstream is only reading the LAST LINE in my loop (take>>reg;).

So my reg variable is only the last line for each loop...
Why are you trying to write to a file then read back from the same file immediately?
You cannot guarantee your work has been written to the file because of flushing io etc. After you have finished writing to the file, flush and close the handle. THEN create and open the handle for reading.
I need to have the user enter in the number of registrants for each company and then read back this number from the file to figure out cost, etc. and then output the cost, etc. into a new file.

This is an intro class so I'm not sure what you mean about flushing IO.

Thank you.
Thank you! I've figured it out thanks to your help. But I think I was actually supposed to put my own integers into the Register.txt file instead of having the user enter them in. Oh well. Thanks!
Topic archived. No new replies allowed.