issue with ofstream dataout - c++

In my program, my dataout: void outfile is not writing to the file, can anyone figure out why?
using namespace std;
#include<iostream>
#include<cmath>
#include<iomanip>
#include<fstream>
// Declaration of functions used
void writetable (double, double, double, double);
void tableout (double, double, double, double);
void secant(double, double, double, double, double, double, double, double, double, double&, int&);
void writedata (double, double, double);
void outfile(double, double, double&);
double fx( double, double, double, double, double, double, double);
const double tol=0.0001; // Tolerance for convergence
const int max_iter=50; // Maximum iterations allowed
// main program
int main()
{
int iteration; // Number of iterations
double kr, uc, q, b, radians;
double x0, x1; // Starting values for x
double root; // Root found by secant method
const double PI = 4.0*atan(1.0);
ifstream datain ("shuttle.txt");
ofstream dataout ("results.txt");
datain >> kr >> uc >> q >> b;
x0= 1000;
x1 = 200;
writetable(kr, uc, q, b);
tableout(kr, uc, q, b);
for (double angle = 10; angle <= 70; angle += 15)
{
for (double velocity = 16000; velocity <= 17500; velocity += 500)
{
radians= angle * PI/180 ;
//cout << velocity << endl;
// cout << radians << endl;
// cout << angle << endl;
secant (radians, velocity, kr, uc, q, b, x0, x1, angle, root, iteration);
writedata(angle, velocity, root);
}
}
system("pause");
}
// Definition of function "secant"
// Receives a, b, c, d and x0 values from main program
// Returns root and the iterations required
void secant(double radians, double velocity, double kr, double uc, double q, double b, double x0, double x1, double angle, double& root, int& iteration)
{
double xnminus1, xnplus1, xn; // Local variables
iteration=0; // Initialize iterations
xnminus1=x0;
xn=x1;
do
{
++iteration;
xnplus1 = xn - fx(radians, velocity, kr, uc, q, b, xn)*(xn-xnminus1)/
(fx(radians, velocity, kr, uc, q, b, xn)-fx(radians, velocity, kr, uc, q, b, xnminus1));
//cout<<"x"<<iteration+1<<" = "<<xnplus1<<endl;
xnminus1 = xn;
xn=xnplus1;
}
while ((fabs(fx(radians, velocity, kr, uc, q, b, xnplus1)) >= tol )&& (iteration < max_iter));
root=xnplus1;
//cout<<"\nThe root is = "<<root<<endl;
//cout<<"The number of iterations was = "<<iteration<<endl;
//cout<<"The value of f(x) at the root = "<<fx(radians, velocity, kr, uc, q, b, root)<<endl<<endl;
outfile(angle, velocity, root);
}
// Defines "fx"
double fx(double radians,double velocity, double kr, double uc, double q, double b, double ts)
{
return kr * pow(ts,4.0) + uc * ts - q - pow((velocity / b), 2.0) * sin(radians);
}
void writetable(double kr, double uc, double q, double b)
{
cout <<endl << "Input Parameters:" <<endl;
cout<< "Kr(1/K^2)=" << kr << endl << "uc(1/K)=" << uc <<endl << "q(unitless)=" << q << endl << "b(mph)=" << b<< endl;
cout << " angle..............velocity...........surface temp..............safe..........";
cout << " degs...............mph................Kelvin.....................?............";
cout << "--------------------------------------------------------------------------------";
}
void writedata (double angle, double velocity, double root)
{
cout << left << " " << angle << " "<< velocity << " "<< fixed << setprecision(0) << setw(5) <<root<< " ";
if(root <1000)
cout << "safe"<< endl;
else
cout << "unsafe" <<endl;
}
void tableout(double kr, double uc, double q, double b)
{
ofstream dataout ("results.txt");
dataout<<endl << "Input Parameters:" <<endl;
dataout<< "Kr(1/K^2)=" << kr << endl << "uc(1/K)=" << uc <<endl << "q(unitless)=" << q << endl << "b(mph)=" << b<< endl;
dataout << " angle..............velocity...........surface temp..............safe.........."<< endl;
dataout << " degs...............mph................Kelvin.....................?............"<< endl;
dataout << "--------------------------------------------------------------------------------"<< endl;
}
void outfile (double angle, double velocity, double& root)
{
ofstream dataout ("results.txt");
dataout << left << " " << angle << " "<< velocity << " "<< fixed << setprecision(0) << setw(5) <<root<< " ";
if(root <1000)
dataout << "safe"<< endl;
else
dataout << "unsafe" <<endl;
}

Is the open in outfile succeeding. You've opened the file for output in main; some systems won't allow the same file to be opened twice, or opened twice for output. (Since you don't use the open file in main, why open it there?)

Related

VS2022 code analysis error using uninitialized memory C++ [duplicate]

This question already has answers here:
Uninitialized variable behaviour in C++
(4 answers)
What happens when I print an uninitialized variable in C++? [duplicate]
(4 answers)
Calling function with variable that is being initialized [duplicate]
(1 answer)
Closed 5 months ago.
Here are the errors on the following code after the VS2022(v143) upgrade:
Could someone please suggest what is wrong here and how to fix it?
//Cricle properties problem
#include <iostream>
using namespace std;
float Qradius(float diameter)
{
float radius = diameter / 2;
return radius;
}
float Warea(float radius)
{
float area = (radius *radius) *3.14;
return area;
}
float Ecircumference(float diameter)
{
float circumference = 3.14 * diameter;
return circumference;
}
float Rarclength(float arcangle, float circumference)
{
float arclength = (circumference *arcangle) / 360;
return arclength;
}
int main()
{
float diameter, arcangle;
float area, circumference, arclength, radius;
cout << "Type the diameter ";
cin >> diameter;
cout << "Type the arcangle ";
cin >> arcangle;
cout << "The radius of the circle is " << Qradius(diameter) << endl;
cout << "The area is " << Warea(radius) << endl;
cout << "The circumference is " << Ecircumference(diameter) << endl;
cout << "The arc length is " << Rarclength(arcangle, circumference) << endl;
}
I solved the warnings and explained why they were coming up in the comments in the code. Also do not use using namespace std;
#include <iostream>
float Qradius(float diameter)
{
float radius = diameter / 2;
return radius;
}
float Warea(float radius)
{
// if no f is specified, the compiler assumes it is a double
// the warning tells you that it converts a double to float
// which could lead to loss of data (C4244)
float area = (radius *radius) * 3.14f;
return area;
}
float Ecircumference(float diameter)
{
// same as aboth
float circumference = 3.14f * diameter;
return circumference;
}
float Rarclength(float arcangle, float circumference)
{
float arclength = (circumference *arcangle) / 360;
return arclength;
}
int main()
{
float diameter, arcangle;
// area and arclength are unused (C4101)
float /*area,*/ circumference, /*arclength,*/ radius;
std::cout << "Type the diameter ";
std::cin >> diameter;
std::cout << "Type the arcangle ";
std::cin >> arcangle;
// radius and circumference is never set
// and later used without setting any value (C6001)
radius = Qradius(diameter);
circumference = Ecircumference(diameter);
std::cout << "The radius of the circle is " << radius << std::endl;
std::cout << "The area is " << Warea(radius) << std::endl;
std::cout << "The circumference is " << circumference << std::endl;
std::cout << "The arc length is " << Rarclength(arcangle, circumference) << std::endl;
}

ofstream doesn't write different data to two different files

I'm having trouble using ofstream to write two different outputs to two different files at once. The program compiles and runs fine, and writes data to p1output.txt, but when I open p2output.txt, it is blank except for the first line with contents:
Time x1 x2 v1 v2 Energy Angular Momentum
If I delete the lines of code that write data to p1output.txt the program writes data correctly to p2output.txt. The only thing I can think of is that having two Leapfrog functions one after the other somehow prevents the second one from executing and printing out data. I don't know why this is or how to fix it - can anybody help?
Here is the code:
#include <iostream>
#include <cmath>
#include <fstream>
using namespace std;
#define D 2 // number of dimensions
struct particle
{
double x[D] ; // (x,y) coordinates
double v[D] ; // velocity
double F[D] ; // Force
double a[D] ; // acceleration
double GMm ; // gravitational parameter
double im ; // inverse mass
double PE ; // potential energy
double T ; // kinetic energy
double E ; // total energy
double J; // angular momentum
double r ; // distance from origin
};
void accel(particle &p_n) // acceleration of particle
{
for (int i=0; i<D; i++ )
{
p_n.a[i]=p_n.x[i]/(p_n.r*p_n.r*p_n.r) ;
}
}
void ForceEnergy(particle &p_n) //force and energy of particle
{
double R=0.0;
for(int i=0; i<D; i++)
{
R+=p_n.x[i]*p_n.x[i];
}
double r=sqrt(R);
p_n.PE=-p_n.GMm/r ; // PE of particle
p_n.r=r; // absolute distance of particle from origin
for(int i=0; i<D; i++)
{
p_n.F[i]=-p_n.GMm*p_n.x[i]/(p_n.r*p_n.r) ;
}
p_n.T=0.0;
for(int i=0; i<D; i++)
{
p_n.T+=0.5*p_n.v[i]*p_n.v[i]/p_n.im;
}
p_n.E=p_n.T+p_n.PE;
}
void VectorProduct(double x[],
double y[],
double z[],
int N) // finding the cross product of 2 vectors
{
double d[3], e[3];
for(int i=0; i<3; i++)
{
d[i]=0;
e[i]=0;
}
for(int i=0; i<N; i++)
{
d[i]=x[i];
e[i]=y[i];
}
z[0]=d[1]*e[2]-d[2]*e[1];
z[1]=d[2]*e[0]-d[0]*e[2];
z[2]=d[0]*e[1]-d[1]*e[0];
}
double VectorMag(double u[] ,
int n) // calculates magnitude of a vector
{
double vm=0;
for(int i=0; i<n; i++)
{
vm=vm+u[i]*u[i];
}
return sqrt(vm);
}
void AngMom(particle &p_n) // finding angular momentum about the origin
{
double z[3];
VectorProduct(p_n.x,
p_n.v,
z,
D);
p_n.J=VectorMag(z,3)/p_n.im;
}
void xchange(particle &p_n ,
double dt) // position increment
{
for(int i=0; i<D; i++)
{
p_n.x[i]+=dt*p_n.v[i] ;
}
}
void vchange(particle &p_n ,
double dt) // momentum increment
{
for(int i=0; i<D; i++)
{
p_n.v[i]+=dt*p_n.a[i] ;
}
}
void ParticleState(particle p_n ,
double t,
const char filename[]) // printing out the particle state
{
ofstream fxout;
fxout.open(filename,
ios::app);
if(fxout.good()==false)
{
cerr << "can't write to file " << filename << endl;
exit(0);
}
else
{
fxout << t << "\t" << p_n.x[0] << "\t" << p_n.x[1] << "\t"<< p_n.v[0] << "\t" << p_n.v[1] << "\t"<< p_n.E << "\t"<< p_n.J << endl;
fxout.close();
}
}
void Leapfrog(particle &p_n,
double dt,
double &t,
int N,
const char filename[])
{
while(t < N)
{
ParticleState(p_n,
t,
filename);
xchange(p_n,
dt*0.5); // position moved by a half-step
t+=0.5*dt;
accel(p_n); // computes acceleration at this position
vchange(p_n,
dt); // velocity moved by a full-step
xchange(p_n,
dt*0.5) ; // position moved by another half-step
t+=0.5*dt ;
}
}
int main()
{
particle p_1, p_2;
double dt=0.01; // time per step
double t=0.0; // start time
int N=1000; // number of time steps
p_1.im=0.02; p_2.im=0.5;
p_1.v[0]=0; p_2.v[0]=1;
p_1.v[1]=20; p_2.v[1]=20;
p_1.x[0]=4; p_2.x[0]=4;
p_1.x[1]=4; p_2.x[1]=4;
p_1.GMm=100;
p_2.GMm=100;
ForceEnergy(p_1);
accel(p_1);
AngMom(p_1);
ForceEnergy(p_2);
accel(p_2);
AngMom(p_2);
ofstream f1out;
f1out.open("p1output.txt");
f1out << "#Time" << "\t" << "x1" << "\t" << "x2" << "\t" << "v1" << "\t" << "v2" << "\t" << "Energy" << "\t" << "Angular Momentum" << endl;
f1out.close();
ofstream f2out;
f2out.open("p2output.txt");
f2out << "#Time" << "\t" << "x1" << "\t" << "x2" << "\t" << "v1" << "\t" <<"v2" << "\t" << "Energy" << "\t" << "Angular Momentum" << endl;
f2out.close();
Leapfrog(p_1,
dt,
t,
N,
"p1output.txt");
Leapfrog(p_2,
dt,
t,
N,
"p2output.txt");
return 0;
}
You taking "t" by reference.So when you write parameters for p2output.txt "t" is already greater than "N".So it not goes into while(t < N) loop.Try removing "&" from void Leapfrog(particle &p_n,
double dt,
double t,
int N,
const char filename[])

C++ Error: no matching function for call

I am trying to solve a quadratic equation using the bisection method. When trying to evaluate the roots I get this error: "no matching function for call".
#include "assign4.h"
#include <iostream>
using namespace std;
int main(int argc, char * argv[]){
solution s;
double root;
cout << "Enter interval endpoints: ";
cin >> s.xLeft >> s.xRight;
cout << "Enter tolerance: ";
cin >> s.epsilon;
root = s.bisect (s.xLeft, s.xRight, s.epsilon, s.f, s.error);
if (!(s.error))
cout << "Root found at " << root << "\nValue of f(x) at root is: " << s.f(root);
else
cout << "The solution of a quadratic equation with coefficients: " << endl;
cout << "a = " << a << ", b = " << b << ", c = " << c << endl;
cout << "has not been found." << endl;
return 0;
}
The error occurs where root = ... it seems to have a problem with my function f but I don't understand what is wrong. The following two bits of code are my class and class implementation files. We just started working with classes so I am uncertain if my problem lies there or simply in the above code.
#ifndef ASSIGN4_H
#define ASSIGN4_H
class solution {
public:
double xLeft, xRight;
double epsilon;
bool error;
double bisect(double, double, double, double f(double), bool&);
double f(double);
};
#endif // ASSIGN4_H
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#include "assign4.h"
#include <iostream>
#include <cmath>
using namespace std;
double solution::bisect (double xLeft, double xRight, double epsilon, double func(double), bool& error) {
double xMid;
double fLeft, fRight;
double fMid;
fLeft = f(xLeft);
fRight = f(xRight);
error = (fLeft * fRight) > 0;
if (error)
return -999.0;
while (fabs (xLeft - xRight) > epsilon) {
xMid = (xLeft + xRight) / 2.0;
fMid = f (xMid);
if (fMid == 0.0)
return xMid;
else if (fLeft * fMid < 0.0)
xRight = xMid;
else
xLeft = xMid;
cout << "New Interval is [" << xLeft << ", " << xRight << "]" << endl;
}
return (xLeft + xRight) / 2.0;
}
double solution::f (double x) {
return ((5 * pow(x,2.0)) + (5 * x) + 3);
}
The 4th parameter is a function pointer,
double bisect(double, double, double, double f(double), bool&);
When you call this function:
root = s.bisect (s.xLeft, s.xRight, s.epsilon, s.f, s.error);
While the member fiction double f(double) is not the same type as that parameter because this is C++ member function and not static, so the 'this' parameter is added this member function when compiling.
type add the static key word to the function.
The syntax for a function pointer is usually: double (*f)(double). Aside from that, you are attempting to pass a member function through a non-member-function pointer. Since your function does not use any member variables, the simplest solution would be to make it static:
class solution {
// ...
static double f(double);
};
If you want to use pointers to member functions.
Change
double bisect(double, double, double, double f(double), bool&);
to
double bisect(double, double, double, double (solution::*f)(double), bool&);
in declaration and definition.
Change the call from
root = s.bisect (s.xLeft, s.xRight, s.epsilon, s.f, s.error);
to
root = s.bisect (s.xLeft, s.xRight, s.epsilon, &solution::f, s.error);
This is what I have that compiles and links successfully for me.
#include <iostream>
#include <typeinfo>
#include <math.h>
using namespace std;
class solution {
public:
double xLeft, xRight;
double epsilon;
bool error;
double bisect(double, double, double, double (solution::*f)(double), bool&);
double f(double);
};
using namespace std;
double solution::bisect (double xLeft, double xRight, double epsilon, double (solution::*func)(double), bool& error) {
double xMid;
double fLeft, fRight;
double fMid;
fLeft = (this->*func)(xLeft);
fRight = (this->*func)(xRight);
error = (fLeft * fRight) > 0;
if (error)
return -999.0;
while (fabs (xLeft - xRight) > epsilon) {
xMid = (xLeft + xRight) / 2.0;
fMid = (this->*func)(xMid);
if (fMid == 0.0)
return xMid;
else if (fLeft * fMid < 0.0)
{
xRight = xMid;
fRight = fMid;
}
else
{
xLeft = xMid;
fLeft = fMid;
}
cout << "New Interval is [" << xLeft << ", " << xRight << "]" << endl;
}
return (xLeft + xRight) / 2.0;
}
double solution::f (double x) {
return ((5 * pow(x,2.0)) + (5 * x) + 3);
}
int main(int argc, char * argv[]){
solution s;
double root;
cout << "Enter interval endpoints: ";
cin >> s.xLeft >> s.xRight;
cout << "Enter tolerance: ";
cin >> s.epsilon;
root = s.bisect (s.xLeft, s.xRight, s.epsilon, &solution::f, s.error);
if (!(s.error))
cout << "Root found at " << root << "\nValue of f(x) at root is: " << s.f(root) << endl;
else
{
cout << "The solution of a quadratic equation with coefficients: " << endl;
// cout << "a = " << a << ", b = " << b << ", c = " << c << endl;
cout << "has not been found." << endl;
}
return 0;
}
I believe it has to do with your callback function. Typically you get that kind of compiler error when you use an incorrect function call. If you want this kind of callback function, you may want to look into function pointers.
http://www.cprogramming.com/tutorial/function-pointers.html

Having trouble outputting using class

I am having trouble with the output part of the problem, I am getting errors on the lines that say bottom right, top left, and dimension. What am i doing wrong?
I have tried many things and I just do not know how to get it to work correctly, and we have not gone over anything like this kind of output in class:
#include <iostream>
#include <cmath>
using namespace std;
class Point
{
private:
double px;
double py;
public:
void setX(const double x);
void setY(const double y);
double getX() const;
double getY() const;
};
class Triangle
{
private:
Point blPoint;
double length, height;
public:
// member functions
void setBottomLeftX(const double x);
void setBottomLeftY(const double y);
void setLength(const double inLength);
void setHeight(const double inHeight);
Point getBottomLeft() const;
Point getBottomRight() const;
Point getTopLeft() const;
double getLength() const;
double getHeight() const;
double perimeter() const;
double hypotenuse() const;
void scaleLength(const double sx);
void scaleHeight(const double sy);
void display() const;
};
// FUNCTION PROTOTYPES GO HERE:
double read_triangle(Triangle & tri);
int main()
{
// Define local variables
Triangle tri;
double sx, sy;
//Prompt the user for triangle information and fill Class Triangle object, tri,
//with this information
read_triangle(tri);
// Display triangle information
tri.display();
// Prompt and read scale factors to change length and height
cout << "Enter scale factor in x direction: ";
cin >> sx;
cout << "Enter scale factor in y direction: ";
cin >> sy;
// Apply scale factors
tri.scaleLength(sx);
tri.scaleHeight(sy);
// Display triangle information
tri.display();
return 0;
}
// FUNCTION DEFINITIONS GO HERE:
// CLASS MEMBER FUNCTION DEFINITINOS GO HERE:
void Point::setX(const double x)
{
px = x;
}
void Point::setY(const double y)
{
py = y;
}
double Point::getX() const
{
return (px);
}
double Point::getY() const
{
return (py);
}
void Triangle::setBottomLeftX(const double x)
{
/* INSERT YOUR CODE */
blPoint.setX(x);
}
void Triangle::setBottomLeftY(const double y)
{
/* INSERT YOUR CODE */
blPoint.setY(y);
}
void Triangle::setLength(const double inLength)
{
/* INSERT YOUR CODE */
length=inLength;
}
void Triangle::setHeight(const double inHeight)
{
/* INSERT YOUR CODE */
height=inHeight;
}
Point Triangle::getBottomLeft() const
{
/* INSERT YOUR CODE */
return (blPoint);
}
Point Triangle::getBottomRight() const
{
/* INSERT YOUR CODE */
Point getBottomRight;
double mx = (blPoint.getX()+ length);
getBottomRight.setX(mx);
return(getBottomRight);
}
Point Triangle::getTopLeft() const
{
/* INSERT YOUR CODE */
Point getTopLeft;
double my = (blPoint.getY()+ height);
getTopLeft.setY(my);
return (getTopLeft);
}
double Triangle::getLength() const
{
/* INSERT YOUR CODE */
return (length);
}
double Triangle::getHeight() const
{
/* INSERT YOUR CODE */
return (height);
}
double Triangle::hypotenuse() const
{
/* INSERT YOUR CODE */
//hypotenuse = (sqrt((height * height)+(length * length)));
return (sqrt((height * height)+(length * length)));
}
double Triangle::perimeter() const
{
/* INSERT YOUR CODE */
//perimeter = ((sqrt((height * height)+(length * length)))+ height + length);
return ((sqrt((height * height)+(length * length)))+ height + length);
}
void Triangle::scaleLength(const double scalefact)
{
/* INSERT YOUR CODE */
length = scalefact * length;
}
void Triangle::scaleHeight(const double scalefact)
{
/* INSERT YOUR CODE */
height = scalefact * height;
}
void Triangle::display() const
{
/* INSERT YOUR CODE */
cout <<"---------------------------------------" << endl;
cout << "Lower Left Vertex (" << blPoint.getX() << ", " << blPoint.getY() << ')' <<endl;
cout << "Top Left Vertex (" << blPoint.getX() << ", " << getTopLeft.getY() << ')' << endl;
cout << "Bottom Right Vertex (" << getBottomRight.getX() << ", " << blPoint.getY() << ')' << endl;
cout << "Dimensions (" << getBottomRight.getX()- blPoint.getX() << ", " << getTopleft.getY() - blPoint.getY() << ')' << endl;
cout << "Hypotenuse = " << hypotenuse() << endl;
cout << "Perimeter = " << perimeter() << endl;
cout <<"---------------------------------------" << endl;
}
double read_triangle(Triangle & tri)
{
/* INSERT YOUR CODE */
double x, y, inLength, inHeight;
cout << "Enter bottom left x coordinate: ";
cin >> x;
tri.setBottomLeftX(x);
cout << "Enter bottom left y coordinate: ";
cin >> y ;
tri.setBottomLeftY(y);
cout << "Enter length: ";
cin >> inLength;
tri.setLength(inLength);
cout << "Enter Height: ";
cin >> inHeight;
tri.setHeight(inHeight);
}
You are using the functions like they are variables you need to add () to call them correctly:
cout << "Top Left Vertex (" << blPoint.getX() << ", " << getTopLeft().getY() << ')' << endl;
^^
cout << "Bottom Right Vertex (" << getBottomRight().getX() << ", " << blPoint.getY() << ')' << endl;
^^
cout << "Dimensions (" << getBottomRight().getX()- blPoint.getX() << ", " << getTopLeft().getY() - blPoint.getY() << ')' << endl;
^^ ^^
Also, read_triangle does not have a return statement but you declare that it returns double. Flowing off the end of a value returning function is undefined behavior and therefore you can not rely on the results. It does not look like you are using the results so you may want to just change the function to return void and that will fix it.

converting to int from float

#include <iostream>
using namespace std;
int main(){
float const PI = 3.1415926;
int radius = 4;
int peri = 0;
int area = 0;
peri =(float) (PI * 2)* radius;
area = (float) PI * (radius * radius);
cout << "Radius is " << radius << endl;
cout << "Perimeter is " << peri << endl;
cout << "Area is " << area << endl;
return 0;
};
peri and area are not converting to float and always receiving a warning "converting to int from float" what seems to be the problem ..
If you really want to truncate peri and area to integers, you should do so explicitly:
peri=static_cast<int>(2*PI*radius);
area=static_cast<int>(PI*radius*radius);
Otherwise, you'll get a warning and it will look like a mistake to anyone who reads your code.