if语句输入(cin)

时间:2012-05-16 03:38:34

标签: c++

练习一些C ++,我从一本书中遇到了一些代码。 断句的if语句的用法对我来说有点不必要:

if(!(cin>> dstep)) 打破;

这对我来说有点hackish,只是使用cin>> dstep没有if或break运行程序正常。有什么想法吗?

                    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;
                }

1 个答案:

答案 0 :(得分:3)

您必须启用异常或检查每个流输入操作,否则当输入格式错误时,您可能会陷入无限循环,或者只是得到错误的结果。