【问题标题】:Can anyone figure out why my loops are falling through?谁能弄清楚为什么我的循环会失败?
【发布时间】:2018-08-23 02:44:25
【问题描述】:

这是我在这里的第一篇文章。我是 C++ 新手(上周才开始),花了几个小时在这上面,我很难过。

我知道我在这个程序中可能做错了很多事情,但我向你们保证我已经尽力了。验证输入超出了我的作业范围,但我想尝试一下,因为只是获取输入并返回它们很无聊。

基本上,输入验证适用于外部循环,但对于内部循环,即使无效也会失败。

#include <iostream>
using namespace std;

//Global Variables

int cubeLength = 0;
int cubeWidth = 0;
int cubeHeight = 0;
int cubeSurfaceArea = 0;
int cubeVolume = 0;
bool valid = false;

int main() {

//Ask user for cubeLength and validate input for integer values
do {
cout << "Please enter a numerical value for the length of a cube" <<endl;
cin >> cubeLength;
    if (cin.good()) {
        valid = true;
        //Ask user for cubeWidth and validate input for integer values
        do {    
            cout << "Please enter a numerical value for the width of a cube" <<endl;
            cin >> cubeWidth;
            if (cin.good()) {
                valid = true;
                //Ask user for cubeHeight and validate input for integer values
                do {
                    cout << "Please enter a numerical value for the height of a cube" <<endl;
                    cin >> cubeHeight;
                    if (cin.good()) {
                        valid = true;
                    }
                    else
                    {   
                        cin.clear();
                        cin.ignore(INT_MAX, '\n');
                        cout << "Invalid cube height. Please try again" << endl;
                    }
                }while (!valid);
            }
            else
            {   
                cin.clear();
                cin.ignore(INT_MAX, '\n');
                cout << "Invalid cube width. Please try again" << endl;
            }
        }while (!valid);
    }
    else
    {   
        cin.clear();
        cin.ignore(INT_MAX, '\n');
        cout << "Invalid cube length. Input is not an integer" << endl;
    }
} while (!valid);


//Perform calculations for surface area and volume then assign them to their associated variables
if (cubeLength >= 1 && cubeWidth >= 1 && cubeHeight >= 1)
    {
        valid = true;
        cubeSurfaceArea = ((2*(cubeWidth*cubeLength))+(2*(cubeLength*cubeHeight))+(2*(cubeWidth*cubeHeight)));
        cubeVolume = (cubeWidth*cubeLength*cubeHeight);
    }
    else {
        cout << "Sorry, one or more cube inputs is invalid. Ending program. Please restart and try again." << endl;
        return 0;
    }   

//Output surface area and volume to user
cout << "Length = " << cubeLength << " Width = " << cubeWidth << " Height = " << cubeHeight << endl;
cout << "The surface area of your cube is " << cubeSurfaceArea << "." << endl;
cout << "The volume of your cube is " << cubeVolume << "." << endl;

//Pause system and end program
return 0;
}

我在底部添加了用于计算的 if 语句,以防止它在整个程序中一直下降并退出。

我还在本网站和其他网站上检查了很多关于验证整数和循环输入的类似问题,但一直无法弄清楚。我的理论是我要么弄乱了有效的布尔逻辑,要么使用了错误的循环方法。

【问题讨论】:

  • 你确定 cin.good() 是你想要做的正确调用吗?文档建议这将检查 cin 流的状态是否存在 EOF 或读/写失败,这听起来不像是要验证流的实际内容......
  • cin.good 在评估时适用于第一个循环,所以作为一个新手,这就是我解决的问题。我可以输入小数和字符串,并且每次都应该是无效的,但是我认为失败是在布尔逻辑中。我也很难找到关于 cin.good 的好的文档,你有什么建议我可以看/应该注意吗?真的很感激。
  • 测试实际输入操作一般比较好,比如if(cin &gt;&gt; foo) ...
  • @B00489663 对此有一些参考,cplusplus.com/reference/ios/ios/good 就是其中之一。基本上我不确定编写的代码是否符合您的预期。

标签: c++ loops validation int cin


【解决方案1】:

循环的主要问题是您将valid 设置为true,但从未设置为false,因此语句while (!valid) 永远不会计算为false。

另一个普遍的评论是代码的布局有太多的嵌套循环。这可以简化很多。

我没有测试下面的代码,但是这种类型的结构更容易阅读 - 即分别进行每个输入,而不是将所有输入混在一起! :-)

//Ask user for cubeLength and validate input for integer values
valid = true;
do {
     cout << "Please enter a numerical value for the length of a cube" <<endl;
     cin >> cubeLength;
     if (!cin.good()) {
        valid = false;
        cin.clear();
        cin.ignore(INT_MAX, '\n');
        cout << "Invalid cube length. Input is not an integer" << endl;
    }     
} while (!valid);

//Ask user for cubeWidth and validate input for integer values
do {
    cout << "Please enter a numerical value for the width of a cube" <<endl;
    cin >> cubeWidth;
    if (!cin.good()) {
        valid = false;
        cin.clear();
        cin.ignore(INT_MAX, '\n');
        cout << "Invalid cube width. Please try again" << endl;
   }    
} while (!valid);


//Ask user for cubeHeight and validate input for integer values
do {
    cout << "Please enter a numerical value for the width of a cube" <<endl;
    cin >> cubeWidth;
    if (!cin.good()) {
        valid = false;
        cin.clear();
        cin.ignore(INT_MAX, '\n');
        cout << "Invalid cube height. Please try again" << endl;
    } 
 }while (!valid);

【讨论】:

  • 感谢您的回复,我的直觉是布尔逻辑,所以我会回去弄乱它,看看我是否可以做到。我确实尝试在 else 语句中将其设置为 false,但我上次尝试时仍然失败。我最初没有嵌套循环,我已经移动了很多东西。首先它们只是连续的 if 语句,然后我尝试了 do while 循环,然后我尝试将它们分成各自的函数用于每个输入。每个配置都产生相同的结果。不过总的来说,我喜欢任何改进代码布局/结构的技巧。
  • @B00489663 看看这读起来有多简单。即使仍然重复了很多代码,所以有机会制作一个函数作为下一步 - 快乐学习!
  • 绝对容易得多,我想我在代码不工作时陷入了过于复杂的代码的陷阱。感谢您的宝贵时间!
  • @B00489663 好的,不用担心。您需要接受答案或投票,以便其他人可以看到它已完成。
  • 不幸的是我不能,因为这是我的第一篇文章。今天刚刚为学校注册了帐户,所以我没有足够的积分来投票或选择最佳答案。不过,你帮我真是太棒了。
【解决方案2】:

第一次设置valid = true 后,它会一直保持true 直到结束。在再次测试之前,您应该将其带回false

【讨论】:

    【解决方案3】:

    感谢所有提供帮助和反馈的人:

    这个问题现在对我来说非常明显,即在输入验证失败后,布尔值在循环开始时没有被重置。

    我根据建议重新编写了整个代码,现在有一个稳定的程序!:)

    #include <iostream>
    using namespace std;
    
    //Global Variables
    
    int cubeLength = 0;
    int cubeWidth = 0;
    int cubeHeight = 0;
    int cubeSurfaceArea = 0;
    int cubeVolume = 0;
    bool valid = true;
    char choice;
    
    int main() {
    do {
    //Ask user for cubeLength and validate input for integer values
    do {
    valid = true;
    cout << "Please enter a numerical value for the length of a cube" <<endl;
    cin >> cubeLength;
        if (cin.fail()) {
            valid = false;
            cin.clear();
            cin.ignore(INT_MAX, '\n');
            cout << "Invalid cube length. Input is not an integer" << endl;
            }
        } while (!valid);
    
    //Ask user for cubeWidth and validate input for integer values
    do {    
        valid = true;
        cout << "Please enter a numerical value for the width of a cube" <<endl;
        cin >> cubeWidth;
        if (cin.fail()) {
            valid = false;  
            cin.clear();
            cin.ignore(INT_MAX, '\n');
            cout << "Invalid cube width. Input is not an integer" << endl;
        }
    } while (!valid);
    //Ask user for cubeHeight and validate input for integer values
    do {
        valid = true;
        cout << "Please enter a numerical value for the height of a cube" <<endl;
        cin >> cubeHeight;
        if (cin.fail()) {   
            valid = false;
            cin.clear();
            cin.ignore(INT_MAX, '\n');
            cout << "Invalid cube height. Input is not an integer" << endl;
        }
    }while (!valid);
    
    //Perform calculations for surface area and volume then assign them to their associated variables
    if (cubeLength >= 1 && cubeWidth >= 1 && cubeHeight >= 1)
        {
            cubeSurfaceArea = ((2*(cubeWidth*cubeLength))+(2*(cubeLength*cubeHeight))+(2*(cubeWidth*cubeHeight)));
            cubeVolume = (cubeWidth*cubeLength*cubeHeight);
        }
        else {
            cout << "Sorry, one or more cube inputs is invalid. Ending program. Please restart and try again." << endl;
            return 0;
        }   
    
    //Output surface area and volume to user
    cout << "Length = " << cubeLength << " Width = " << cubeWidth << " Height = " << cubeHeight << endl;
    cout << "The surface area of your cube is " << cubeSurfaceArea << "." << endl;
    cout << "The volume of your cube is " << cubeVolume << "." << endl;
    cout << "Would you like to try again? (y/n)" << endl;
    cin >> choice;
    
    } while (choice != 'n');
    
    //Pause system and end program
    return 0;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-15
      • 1970-01-01
      • 2011-08-15
      相关资源
      最近更新 更多