0

data11.txt:

Length(l) Time(t)   Period(T)
200   10.55     0.527
300   22.72     1.136
400   26.16     1.308
500   28.59     1.429
600   31.16     1.558

ill be taking data from this file above in my code

#include <iostream>
#include <cmath>
#include <fstream>
#include <string>
#include <iomanip>

/*Using data11.txt as reference, write code to read from the file. In a pendulum experiment certain data was recorded in order to calculate the acceleration due to gravity. All calculations should be in their SI units

Write a function to calculate the acceleration due to gravity as the slope of the graph to this equation.T=2πlg−−√.
What is the percentage error in your calculated value? Take g=9.8ms-2.
If the pendulum weighs 50g and is displaced at an angle of 30, what will it maximum kinetic energy value for each length of the string? Display your answer in table form. */

using namespace std;
double slope_gravity(double T1, double T2, double L1, double L2){//slope function
    double T1_inverse = 1/pow(T1,2);
    double T2_inverse = 1/pow(T2,2);
    double difference_T = T2_inverse - T1_inverse;
    double difference_L = (L2 - L1)/100;
    double slope = (difference_T/difference_L);
    return slope;
}

const int n = 4;

int main (){
    ifstream mydata;
    string capture;
    float Length[n], Time[n], Period[n], acc_gravity;//declaring variable
    
    mydata.open("Data11.txt");
    if (mydata.is_open()){
        for (int i=0; i<n+1; i++){
            getline(mydata, capture);
            mydata >> Length[i] >> Time[i] >> Period[i];
        }
        acc_gravity = slope_gravity(Period[1], Period[0], Length[1], Length[0]);//acceleration due to gravity calc
        cout << fixed << showpoint << setprecision(1);
        cout << "The Acceleration Due To Gravity Obtained Experimentally "
             << "from the data11 file is "<<abs(acc_gravity)<<"ms^-2"<<endl;
        cout << "Calculating for Percentage error.............";
        cout <<endl<<endl;
        float percent_error = (abs(acc_gravity)- 9.8) * 100/9.8;//error analysis
        cout << "Percent Error is "<< setprecision(2) << abs(percent_error)<<"%"<<endl;
        cout << endl;
        cout << "Calculating Max Kinetic Energy of pendulum weighing 50g being "
             << "displaced at an angle of 30\n";
        
        cout << setprecision(4);
        float velocity[n], x[n], y;//kinetic energy calc
        double max_KE[n];
        
        for (int j=0; j<n+1; j++){
        x[j] = 2 * acc_gravity * Length[j]/100;
        y = 1 - cos(30);
        velocity[j] = sqrt(x[j] * y);
        
        max_KE[j] = 0.5 * 50/1000 * pow(velocity[j],2);
        }
        
        cout<<endl<<endl;
        
        cout << setprecision(1);
        cout << "Length(m)\tMaximum Kinetic Energy(J)\n";//tabular form display
        for (int k=0; k<n+1; k++){
            cout << Length[k] <<"\t"<< max_KE[k] <<endl;    
            }
            
        }
        mydata.close();
    
    return 0;
}

The objective of the program is in the first comment above.

At the end of the program, i'm supposed to print the values of length and Maximum Kinetic energy to the console in a tabular form. However, in the array Length[0], it prints 31.16, but i extracted data from data11.txt, so there is supposed to be the value 200 instead.

The origin of the problem start with this for loop. The for loop works well by extracting values from data11.txt. so the value of Length[0] is 200 here.

i've tried to check why it is behaving this way. The problem starts here;

    mydata.open("Data11.txt");
    if (mydata.is_open()){
        for (int i=0; i<n+1; i++){
            getline(mydata, capture);
            mydata >> Length[i] >> Time[i] >> Period[i];
        }

But outside the forloop, Length[0] is 31.16. I also noticed that Time[4] has different value from input value which is supposed to be 31.16.

Please any help with this?

  • 1
    You are running past the end of your arrays. They have n elements: 0 through n-1. Your for lop attempts to access 0 through n. Since there is no element n, that is undefined behavior & your program could do anything. – Avi Berger Jul 20 '22 at 01:46
  • If I understand your file format correctly, there is also an error in how you are trying to read it in. Once you fix the array size issue, step though your input loop in a debugger and check what values you are actually reading in. – Avi Berger Jul 20 '22 at 01:53
  • And no provision is made to skip the header line. That's another fatal problem. – Sam Varshavchik Jul 20 '22 at 01:55
  • 1
    You have 5 lines of input and declare arrays of size 4. Going out of bounds might be related. Also, `for (int j=0; j – Chris Uzdavinis Jul 20 '22 at 01:59
  • Wow, i've been trying to figure this thing out for hours, LOL. I just begun programming in c++. it can be so stressful sometimes. Thank very much, i really appreciate your help. – Gilbert Quarshie Jul 20 '22 at 03:08

1 Answers1

-1

What you have noticed is called 'buffer overrun'.

    float Length[n], Time[n], Period[n], acc_gravity;
    // since 'n' is 4, 
    // so the valid range of subscript of Length/Time/Period are [0-3]
    // That means, if you try to write to  Length[4], 
    // that is invalid, often lead to ruin something else.
    
    mydata.open("data11.txt");
    if (!mydata.is_open())
    {
        fprintf(stderr,"failed to open datafile.\n");
        return 1;
    }
    
    for (int i=0; i<n+1; i++){  // here the rang of 'i' is [0 - 4]
        getline(mydata, capture);

        mydata >> Length[i] >> Time[i] >> Period[i]; // so, when i==4, 
                                                     // 'buffer overun' happens here. 
                                                     // 'Time' could be ruined by 'Period'.
    }  

If you want to skip the 'header' line of input file, one possible approach is : "'getline()' once , then enter the loop".

Whatever you choose, just don't 'buffer overrun'. Good luck.:)

grizzlybears
  • 492
  • 2
  • 9