//program asks for two sides of a triangle and computes the hypotenuse, assuming a right triangle //this program illustrates writing to a text file from within a function //by passing the file variable to the function as a parameter //If done, this way, main handles the opening and closing of the file. //the program also shows how the output function can write to the std ostream cout object //ofstream is a special case of ostream #include #include #include using namespace std; void inputSides( float &, float &); //input two side of a right triangle void validateInput (float &); //input validation loop void outputTriangle( ostream &,float,float); //output sides of right triangle and its hypotenuse float calcHypotenuse( float, float); int main() { ofstream outFile; float leg1, leg2, hypotenuse; //triangle legs char answer; //for user response to do another case outFile.open("HYP.TXT"); do { inputSides(leg1, leg2); outputTriangle(outFile, leg1, leg2); outputTriangle(cout, leg1,leg2); cout << "Do another? (Y/N) "; cin >> answer; } while ( answer == 'Y'|| answer == 'y'); outFile.close(); return 0; } void inputSides( float &a, float &b) { cout << "Enter first leg of a right triangle. "; cin >> a; validateInput(a); cout << "Enter second leg of a right triangle. "; cin >> b; validateInput(b); } //end inputSides //validation function ensures positive entries void validateInput(float &x) { while (x <=0) { cout << "Input must be positive. Re-input the side "; cin >> x; } } //end validateInput //outputTriangle first calculates the hypotenuse, probably not the best design. //main() should do this, but I wanted to show how a function can call another function! void outputTriangle(ostream & outf, float a, float b) { float hypotenuse; hypotenuse = calcHypotenuse(a, b); outf << "A right triangle with legs " << a << " and " << b; outf << " has hypotenuse " << hypotenuse << endl; } float calcHypotenuse(float a, float b) { return sqrt(a*a + b*b); }