Reading in from a file

Please do not post links to read in writing into a file tutorials here. I already read them, and did not find an answer.

I wrote a program that reads values for Rate and L from a file. However i do not know how to properly write the file for reading-in in the first place, and it gives me an infinite loop.

Here is the file content:

Rate= 0.25;
L=540;
Rate = 0

Here is the program code:

#include <iostream>
#include <fstream>
#include <cmath>
using namespace std;



int main()

{

ifstream infile("coolfile.dat");
double Rate, L, N, Payment;

N = 12;

infile >> Rate >> L;

while(Rate>0){

Payment = ((Rate * pow((1+Rate),N))/(pow((1+Rate),N) - 1)) * L;

cout << "For " << N << " payments of a loan of " << L << " the monthly payment is " << Payment << endl;

}
infile.close();
return 0;
}


Thank you for your help.
bump
If this is the exact contents of the file:
1
2
3
Rate= 0.25;
L=540;
Rate = 0

then I'd recommend reading each line into a string, using the getline() function.
Then either use a stringstream to parse the data, or use the string functions to find the '=' sign, and split the string accordingly into subtrings. If you use the latter option, you may still need to convert the string into a number, for example using strtod().
The stringstream approach is probably easier.

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
#include <iostream>
#include <string>
#include <sstream>
#include <iomanip>

using namespace std;

int main()
{
    string data= "Rate= 0.25;\nL=540;\nRate = 0";
    istringstream infile(data);
    
    string line;
    while (getline(infile, line))
    {
    	istringstream ss(line);
    	string name;
    	double number = 0.0;
    	getline(ss,name,'=');
    	ss >> number;
    	cout << "Name: " << setw(6) << left << name 
		     << " Number: " << number << endl;    	
    }

    return 0;
}

Name: Rate   Number: 0.25
Name: L      Number: 540
Name: Rate   Number: 0


Lines 10 and 11 are just for this demo, you should use the normal disk file, but the behaviour should be the same in the rest of the code.
Last edited on
Topic archived. No new replies allowed.