简体   繁体   English

断言功能导致程序崩溃

[英]Assert function causes program to crash

I have used assert function to ensure that the first number input is between 1 and 7 (inclusive). 我已经使用assert函数来确保第一个数字输入介于1到7(含)之间。 However, when I execute the program and enter an invalid number, it causes the program to crash. 但是,当我执行程序并输入无效的数字时,它将导致程序崩溃。 So, how is the assert function being of any use here if that's the case? 那么,在这种情况下,assert函数在这里有什么用?

Please correct my implementation where required. 请在需要时更正我的实施。

Code: 码:

#include <iostream>
#include <assert.h>

using namespace std;

int main() {
    int num;
    int n;
    int max;
    cout << "Please enter a number between 1 & 7 \n";
    cin >> num;
    assert(num >= 1 && num <= 7);
    for (int i = 0; i < num; i++) {
        cout << "Please enter number " << (i + 1) << ": ";
        cin >> n;
        if (i == 0) {
            max = n;
        }  
        max = (n > max) ? n : max;
    }
    cout << "The maxmum value is: " << max << endl;
    system("pause");
    return 0;
}

Assert is not what you want here. 断言不是您想要的。 What you need is validation . 您需要的是验证 Assertions are for debugging, for identifying completely invalid program states . 断言用于调试,用于识别完全无效的程序状态 The user entering invalid input is not invalid program state, it's just invalid user input . 输入无效输入的用户不是无效的程序状态,而只是无效的用户输入

To perform validation, you need an if-test. 要执行验证,您需要一个if-test。 You will also need some code ready to handle the case of invalid user input. 您还需要准备一些代码来处理无效用户输入的情况。 There's absolutely no way to prevent the user from providing invalid input (short of insanely aggressive dynamic validation where you capture keyboard events as they occur and prevent those keystrokes from translating into character input to your program, but now we're just getting ridiculous), so you need to react to it when it happens, say, by printing an error message and then asking for more input. 绝对没有办法阻止用户提供无效的输入(缺少疯狂的动态验证,您可以在捕获动态事件时捕获键盘事件,并防止这些击键转换为程序的字符输入,但是现在我们变得很荒谬),因此,您需要在发生这种情况时对此做出反应,例如,打印一条错误消息,然后要求更多输入。

One way of doing this is as follows: 一种方法如下:

do {
    cin >> num;
    if (!(num >= 1 && num <= 7)) {
        cerr << "invalid number; must be between 1 and 7!" << endl;
        num = -1;
    }
} while (num == -1);

Just to expand on that point about assertions, they are supposed to make the program crash. 只是为了扩大关于断言的观点,它们应该使程序崩溃。 An assertion failure means your code is broken and must be fixed before it can be used in real life. 断言失败意味着您的代码已损坏,必须将其修复才能在现实生活中使用。 Assertion failures should never be triggered in production code; 断言失败不应在生产代码中触发; they simply aid in testing and catching bugs. 它们只是帮助测试和捕获错误。

What does the "crash" does? “崩溃”是做什么的? According to me, assert will abort the program execution, maybe as another value other than 0. 据我说,assert 中止程序执行,可能是另一个值,而不是0。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM