program 75 include fstream include iomanip include stdlib include math using

# Program 75 include fstream include iomanip include

This preview shows page 42 - 51 out of 51 pages.

// program 7.5 #include <fstream> #include <iomanip> #include <stdlib> #include <math> using namespace std; int main (){ Example (Cont..) const int MAXCHARS =10; const char fname[MAXCHARS] = "polar.dat"; const int LINES = 6; ofstream outfile; int i; float dist, angle; outfile.open(fname); if (outfile.fail()) Example (Cont..) { cout << "\n Failed to open the data file.\n"; exit (1); } outfile << setiosflags (ios::fixed) << setiosflags (ios::showpoint) << setprecision (1); Example (Cont..) for (i =1; i <= LINES; i++) { cout <<"Enter a distance and angle: "; cin >> dist >> angle; outfile << setw(5) << dist << setw (14) << angle << endl; } outfile.close ( ); return 0; } Example Using the polar.dat file created in program 7.5, write a C++ program that reads this file and creates a second file named xycord.dat. The entries in the new file should contain the rectangular coordinates corresponding to the polar coordinates in the polar.dat file. Polar coordinates are converted to rectangular coordinates using the equations X = r cos Y = r sin Where r is the distance coordinate and is the radian equivalent of the angle coordinate in the polar.dat file. Example (Cont..) // program 7.6 #include <fstream> #include <iomanip> #include <stdlib> #include <math> using namespace std; void calcxy (ifstream &, ofstream &); int main (){ const char MAXCHARS = 15; const char infile[MAXCHARS] = "polar.dat"; Example (Cont..) const char outfile[MAXCHARS] = "xycord.dat"; ifstream in; ofstream out; in.open (infile); if (in.fail ()) { cout << "\n The file can not be opened" << "\n Please check that the file currently exists." << endl; exit (1); } Example (Cont..) out.open (outfile); if (out.fail ()) { cout << "\n Failed to open the data file. \n"; exit (2); } calcxy (in, out); in.close (); out.close (); return 0; } Example (Cont..) void calcxy (ifstream & infile, ofstream & outfile) { const float CONVERT = 3.1416/180.0; const int LINES = 6; int i; float dist, angle; float x, y; outfile << setiosflags (ios::fixed) <<setiosflags(ios::showpoint) << setprecision (2); Example (Cont..) for (i = 1; i <= LINES; i++) { infile >> dist >> angle; cout << "dist =" <<dist<< " angle = " << angle << endl; x = dist* cos(angle*CONVERT); y = dist * sin(angle*CONVERT); outfile << setw (6) << x << setw(10) << y << endl; } } #### You've reached the end of your free preview.

Want to read all 51 pages?

• Fall '18
• Heidar Malki
• Filename, Filename extension, Computer file, random access
• • • 