谁能弄清楚为什么我的循环陷入困境?

时间:2018-08-23 02:44:25

标签: c++ loops validation int cin

这是我在这里的第一篇文章。我是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语句,以防止它在整个程序中退出并退出。

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

3 个答案:

答案 0 :(得分:2)

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

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

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

//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);

答案 1 :(得分:1)

首次设置valid = true后,它将保持true到结束。您应该先将其带回false,然后再进行测试。

答案 2 :(得分:0)

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

这个问题现在对我来说很痛苦,这是布尔值在输入验证失败后没有在循环开始时重置。

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

cmake_minimum_required(VERSION 3.4.1)

add_library( # Sets the name of the library.
             my_library
             # Sets the library as a shared library.
             SHARED
             # Provides a relative path to your source file(s).
             src/main/cpp/c_api.h
             src/main/cpp/native-lib.cpp )

find_library( # Sets the name of the path variable.
              log-lib
              # Specifies the name of the NDK library that
              # you want CMake to locate.
              log )

set(ANDROID_SO_OUTDIR ${CMAKE_HOME_DIRECTORY}/../../../MyUnityProject/Assets/MyLibrary/Plugins/Android/libs)

add_library(tensorflow-lib SHARED IMPORTED)
set_target_properties(tensorflow-lib PROPERTIES IMPORTED_LOCATION
                      ${CMAKE_SOURCE_DIR}/src/main/jniLibs/${ANDROID_ABI}/libtensorflow.so)

target_link_libraries(my_library

                       ${log-lib}
                       tensorflow-lib
                       )
#
# Copy the built library into the appropriate folder in MyUnityProject
#
add_custom_command(TARGET my_library POST_BUILD
   COMMAND ${CMAKE_COMMAND} -E copy
   ${CMAKE_LIBRARY_OUTPUT_DIRECTORY}/libmy_library.so
   ${ANDROID_SO_OUTDIR}/${ANDROID_ABI}/libmy_library.so)