reading a large number of data points from file

I am trying to program a simple allometric equation calculating weights in grams from the natural logarithm of lengths in millimeters: logW = intercept + slope*logL; W = exp(logW).
The attached code compiles and runs, outputting 1000 calculated values of W. BUT all values are simply the values cal;culated on the first data point in the 1000 data point long input file of lengths (LL).
How do I code this so that log W is calculated for each length data point in the input file?

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
  // Allometry.cpp : This file contains the 'main' function. Program execution begins and ends there.
//

#include <iostream>
#include <fstream>
#include <cstdlib>

using namespace std;

int main()
{
    ifstream fin1;
    ifstream fin2;
    ofstream fout;

    fin1.open("C:\\Cpp\\VSProjects\\Allometry\\LWParams.txt");
    fin2.open("C:\\Cpp\\VSProjects\\Allometry\\LL.txt");
    fout.open("C:\\Cpp\\VSProjects\\Allometry\\Weights.txt");

    if (!fin1 || !fin2 || !fout) {
        cerr << "Problem opening the files.\n";
        return 1;
    }

    double ld, slope, length;
    int nreps;

    if (!(fin1 >> ld >> slope >> nreps)) {
        cerr << "Can't read params and/or nreps.\n";
        return 1;
    }

    if (!(fin2 >> length)) {
        cerr << "Can't read params and/or nreps.\n";
        return 1;
    }

    for (int i = 0; i < nreps; i++) {
       double logW = ld + slope * log(length);
       double W = exp(logW);

       fout << W << endl;

    }

}
Maybe something like the following. You may not need nreps if it's simply the number of lengths in LL.txt.

Also, I think you can use forward slashes for directory levels even on Windows (let me know if I'm wrong about that).

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
#include <iostream>
#include <fstream>
#include <string>
#include <cmath>
using namespace std;

int main()
{
    string dir{"C:/Cpp/VSProjects/Allometry/"};
    ifstream fin1(dir + "LWParams.txt");
    ifstream fin2(dir + "LL.txt");
    ofstream fout(dir + "Weights.txt");

    if (!fin1 || !fin2 || !fout) {
        cerr << "Problem opening the files.\n";
        return 1;
    }

    double ld, slope, length;

    if (!(fin1 >> ld >> slope)) {
        cerr << "Can't read params and/or nreps.\n";
        return 1;
    }

    while (fin2 >> length) {
       double logW = ld + slope * log(length);
       double W = exp(logW);
       fout << W << endl;
    }
}

Last edited on
dutch,
Thanks! That works.
Topic archived. No new replies allowed.