0

So I have to write a program to => analyze three different data files, and try to confirm Benford’s law. You will create a console application that opens each file, counts the number of values that start with ‘1’, ‘2’, ‘3’, etc., and then outputs the percentages of each digit.

I think I have it down but I keep getting an error in Dev C++.

int analyzeData(string fname) {
    ifstream infile(string fname);
    int tmp,count = 0;
    float percents[9];
    int nums[9] = { 0 };
    if(!infile.good())
        return 1;
    while(!infile.eof())
    {
        infile >> tmp;
        tmp = first(tmp);
        if(tmp > 0)
        {
            nums[tmp - 1] ++;
            count++;
        }
    }

It's saying that 'good', 'eof', and 'infile' are non-class type? I don't know what that means! Help would be much appreciated! thanks!

CrisL
  • 1
  • 1

2 Answers2

1

Firstly

ifstream infile(string fname);

should be

ifstream infile(fname);

Your version was a function prototype not a declaration of a variable.

Secondly this is the wrong way to loop to the end of a file

while (!infile.eof())
{
    infile >> tmp;
    ...
}

this is the right way

while (infile >> tmp)
{
    ...
}

This must be the single most common error we see here. eof does not do what you think it does, and anyone who told you to write while (!infile.eof()) is just wrong.

Finally first(tmp) is not the correct way to get the first digit from an integer. You'll have to work a little harder than that.

john
  • 85,011
  • 4
  • 57
  • 81
0

Rather than read the input as integers, read the lines as strings, the grab the first digit from the string. Or you could read as an integer and then divide tmp by 10 until the result is < 10.

Make you life a little easier, and use the digit as an index into the array. You need to be able to index values 1 - 9, so you would need to declare your array a little bigger. ditto for percents.

int nums[9] = { 0 };  // works, but do less work
float percents[9];

int nums[10] = { 0 }; // do this, then you can us the digit to index nums[]
float percents[10];

You don't need the guard for tmp > 0, because you have room for all 10 digis,

//if( tmp > 0 )
//{
...
//}

You don't need to subtract one from tmp,

int analyzeData(string fname)
{
    ifstream infile(fname);
    int tmp,count = 0;
    float percents[10];
    int nums[10] = { 0 };
    if(!infile.good())
        return 1;
    while(infile >> tmp)
    {
        tmp = first(tmp);
        {
        nums[tmp] ++;
        count++;
        }
    }
    if(count<1) count=1; //avoid division by zero
    for( tmp=1; tmp<10; ++tmp )
        cout<<tmp<<":"<<nums[tmp]<<",pct:"<<(nums[tmp]*1.0)/count<<eol;
}
ChuckCottrill
  • 4,360
  • 2
  • 24
  • 42