Hello,
I am currently working on a question presented in my homework as follows:
---Modify last week’s area of triangle program so that it loops until valid, usable input is provided.
Here is my code from the previous problem that I am trying to loop.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
|
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
int main()
{
double a,b,c,area,sum,total,newtotal;
cout<<"This program is used to calculate the area of a heronian triangle" "\n";
cout<<"when user inputs a rational number." "\n\n\n";
cout<<"input length a in meters""\n";
cin>>a;
if(cin.fail())
cout<<"Please input a number instead."<<endl;
cout<<"input length b in meters""\n";
cin>>b;
if(cin.fail())
cout<<"Please input a number instead."<<endl;
cout<<"input length c in meters""\n";
cin>>c;
if(cin.fail())
cout<<"Please input a number instead."<<endl;
if(sqrt(pow(a,2)+pow(b,2))>=c){
sum=a+b+c;
total = sum/2;
newtotal = total*(total-a)*(total-b)*(total-c);
newtotal = sqrt(newtotal);
cout<<"The given heronian triangle has an area of "<<newtotal<<"M^2""\n\n";
}else{
cout<<"Invalid dimensions were entered. Please check dimensions and try again\n";
}
system ("PAUSE");
return 0;
}
|
The lines I have bolded with 'cin.fail' are where I have started working on my program. So far it seems to be coming along as now where I input a value other than an integer, I receive my message "Please input a number instead". I am still having a few problems though.
1) I am still having my program try to solve for the non-integer input as 'a'
Is there something I can do to stop this from happening?
Also the program is outputting "Please input a number instead" for all instances a, b, and c when I have only input a non-int for a. Is there an easy way to fix this as well that I'm just skipping over?
2) I am unsure where to start on how to loop my program. Would a 'while' loop be the best way to do this or possibly a 'do-while'?
Sorry for the multiple questions, I am just having a hard time grasping the concept of adding loops into my programs.
Any help would be appreciated, along with a visual possibly of information given as being early on I find it hard to put some things together.
Thanks in advance,
Cameron