从循环中断后结束程序

时间:2016-08-18 13:30:12

标签: c++11

while (1)
{
    cout << "Enter number and unit: ";
    cin >> number;
    cin >> unit;

    if (unit == "in")
    {
        result = 2.54f * number;
        cout << number << " Inches are " << result << " centimeters!" << endl;
    }
    else if (unit == "ft")
    {
        result = 0.3f * number;
        cout << number << " Feet are " << result << " meters!" << endl;
    }
    else if (unit == "yd")
    {
        result = 0.9f * number;
        cout << number << " Yards are " << result << " meters!" << endl;
    }
    else if (unit == "mi")
    {
        result = 1.6f * number;
        cout << number << " Miles are " << result << " kilometers!" << endl;
    }
    else
    {   
        cout << "\tINVALID!!!\n...the program will now exit...\n";
        cin.clear();
        cin >> unit;
        cin >> number;
        break;
    }
}

cout << "Thank you for using English to Metric!\n" << endl;

return 0;}

为了获得最后一个cout并退出程序而不必在休息后输入任何内容,我缺少什么?

1 个答案:

答案 0 :(得分:0)

break子句中的else将退出循环,但在它执行之前

cin.clear();
cin >> unit;
cin >> number;
break;

cin >>是程序等待额外输入的原因。

如果没有它们,则cin.clear()是不必要的,除非您计划稍后执行其他cin操作。

    else
    {
        std::cin.clear();  // optional
        break;
    }
}  // end while
std::cout << "Thank you\n";

会工作。