Practicing some C++, I ran into some code from a book.
The usage of the if statement with the break seams a bit unecessary to me:
if (!(cin >> dstep))
break;
This seams a bit hackish to me and simply using a cin >> dstep with no if or break runs the program fine. Any thoughts?
int main()
{
using namespace VECTOR;
srand(time(0)); //seed random-number generator
double direction;
Vector step; //creates default object
Vector result(0.0, 0.0); //
unsigned long steps = 0;
double target;
double dstep;
cout << "Enter target distance (q to quit): ";
while (cin >> target)
{
cout << "Enter step length: ";
if (!(cin >> dstep)) //if NOT inputing into dstep THEN break/means if INPUTING is TRUE, keep going and don't break out of loop
break;
//cin >> dstep // why not just use this?
while (result.magval() < target)
{
direction = rand() % 360;
step.set(dstep, direction, 'p'); //sets the values dstep and direction based on the form; in this case 'p'
result = result + step;
steps++;
}
cout << "After " << steps << " steps, the subject "
"has the following location:\n";
cout << result << endl;
result.polar_mode();
cout << " or\n" << result << endl;
cout << "Average outward distance per step = "
<< result.magval() / steps << endl;
steps = 0;
result.set(0.0, 0.0);
cout << "Enter target distance (q to quit): ";
}
cout << "Bye!\n";
cin.get();
return 0;
}
You have to either enable exceptions or check every stream input operation, otherwise you risk getting into an infinite loop, or just getting wrong results, when the input is malformed.