函数在返回 false 后不会停止 [关闭]

问题描述 投票:0回答:2

我有 2 个函数 inputCheck 和 getInputs。当我在 getInputs 函数中调用 inputCheck 函数时,它会根据输入返回 false 或 true。但是当它返回 false 时,getInputs 函数不会停止并继续提供输出。在主函数中,如果这有某种关联,我会调用 getInputs 两次。

bool inputCheck(int value, string type) {
    if (value < 0) {
        cout << "Number of " << type << "cannot be smaller than 0.";
        return false;
    }
    return true;
}

bool getInputs(string usage, int& minutes, int& sms, int& internet, int& add_minutes, int& add_sms, int& add_internet) {
    cout << "Please enter how many minutes you used this month " << usage << ": ";
    cin >> minutes;
    inputCheck(minutes, "minutes ");
    cout << "Please enter how many SMSs you sent this month " << usage << ": ";
    cin >> sms;
    inputCheck(sms, "SMSs ");
    cout << "Please enter how many MBs you used this month " << usage << ": ";
    cin >> internet;
    inputCheck(internet, "MBs ");
    cout << "Please specify how many additional packages you bought for calls, SMS and internet in this order: ";
    cin >> add_minutes;
    inputCheck(add_minutes, "additional minutes packages ");
    cin >> add_sms;
    inputCheck(add_sms, "additional sms packages ");
    cin >> add_internet;
    inputCheck(add_internet, "additional internet packages ");
    return true;
}

我尝试对 inputCheck 使用“if”,但没有成功。我需要任何建议来修复它,谢谢。

c++ function boolean return
2个回答
1
投票

为什么

getInputs
功能会停止?您还没有编写任何代码来让它停止。一个函数中的返回只会停止该函数,不会停止任何其他函数。

我想你想写的是这个

bool getInputs(string usage, int& minutes, int& sms, int& internet, int& add_minutes, int& add_sms, int& add_internet) {
    cout << "Please enter how many minutes you used this month " << usage << ": ";
    cin >> minutes;
    if (!inputCheck(minutes, "minutes "))
        return false;
    cout << "Please enter how many SMSs you sent this month " << usage << ": ";
    cin >> sms;
    if (!inputCheck(sms, "SMSs "))
        return false;
    ...
    return true;
}

此代码检查

inputCheck

的返回值
    if (!inputCheck(sms, "SMSs "))

如果它是假的,那么它会停止

getInputs
功能。

        return false;

0
投票

从您的期望和解释来看,您似乎想在代码中编写

if(inputCheck(add_internet, "additional internet packages ") == false) {
    return false;
}

但你没有。你从

inputCheck
返回一些东西然后忽略那个值。

仅仅因为您调用的函数返回

false
不会使当前函数也返回。你需要编写代码来做到这一点。

© www.soinside.com 2019 - 2024. All rights reserved.