c++ - 为什么我的 If/Else 语句 block 没有完全执行?

标签 c++

我正在为我的 CS 类(class)做一个简单的项目。目标是让一个人输入他们购买的每种水果(苹果、香蕉、橙子)的数量,程序计算总数并在最后出示发票。我的教授希望我们也包括一个输入检查,以验证输入是 0 到 100 之间的数字。为此,我有这部分代码。

string name;

int apples, oranges, bananas;
int FRUIT_MAX = 100; 
int FRUIT_MIN = 0; 
float appleCost, orangeCost, bananaCost,
    subTotal, tax, total;

cout << "Welcome to Bob's Fruits, what is your name..." << endl;
getline(cin, name);

cout << "How many apples would you like" << endl;
cin >> apples;
cout << endl;

//checking if user entered a number for apples
if (apples >= FRUIT_MIN && apples <= FRUIT_MAX)
{
    cout << "Thanks" << endl;
}
else //makes the user retype entry if invalid
{
    cout << "Please input a number thats 0 or greater than 0. " << endl;
    cin >> apples;
    cout << endl;
}

cout << "How many oranges would you like" << endl;
cin >> oranges;

    if (oranges >= FRUIT_MIN && oranges <= FRUIT_MAX) //checking to see if number is good
        cout << "Thanks" << endl;
    else //makes the user retype entry if invalid
    {
        cout << "Please input a number thats 0 or greater than 0." << endl;
        cin >> oranges;
        cout << endl;
    }

cout << "How many bananas would you like" << endl;
cin >> bananas;

    if (bananas >= FRUIT_MIN && bananas <= FRUIT_MAX)
        cout << "Thanks";
    else
    {
        cout << "Please input a number thats 0 or greater than 0."; 
        cin >> bananas; 
        cout << endl;
    }

当我输入一个介于 0-100 之间的值时,我会收到正确的“谢谢”输出,然后它会转到下一个问题。当我输入 0-100 以外的数字时,else 语句成功触发,程序要求输入 0-11 之间的数字。

问题出在输入字母时。如果输入一个字母,程序将跳过剩余的每一行,忽略任何额外的 cin 命令,并显示带有所有负数的格式化发票。知道为什么会这样吗?

最佳答案

当 cin 获得无效值时,它会设置一个失败位。

int n;
cin >> n;
if(!cin)
{
    //not a number, input again!
}

您需要使用 cin.ignore() 以便“重置”输入并再次请求输入。

关于c++ - 为什么我的 If/Else 语句 block 没有完全执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28759779/

相关文章:

c++ - 在二进制文件中搜索 C++

c++ - 在 Qt 桌面应用程序中显示主窗体后执行操作

c++ - 带有复制构造函数的多态性

c++ - if 语句和 else if 语句都执行

c++ - 双免腐败

c++ - 如何使用基类的所有派生类填充 vector/列表

c++ - 为什么无符号短(乘)无符号短转换为有符号整数?

c++ - 如何使用 opencv 保存包含多个直方图的文件?

c++ - 字符串分析

c++ - 为什么 Visual C++ 不对最琐碎的代码执行返回值优化?