为什么我的“ main()”函数不会调用void函数?

时间:2019-10-02 14:35:06

标签: c++ function

我正在开发一个程序来帮助我进行世界建设,该程序会根据用户选择的国家(德语,拉丁语,东部)随机生成定居点(村庄,村庄,城镇,城市)。不幸的是,我的代码在“ main()”函数处暂停,因为它不会调用我创建的“ settlementCreation()” void函数。

我尝试将要调用的函数移至“ main()”函数上方,或者将其作为创建函数的常用方法,将其定义在下面,但是这些都不起作用。凭有限的C ++经验,我找不到其他解决方案。

Main()函数:

int main() {
    char tempChoice{};
    bool isMakingSettlement = true;
    while (isMakingSettlement = true) {
        cout << "Create a settlement? (y/n): ";
        cin >> tempChoice;
        cout << "\n\n";
        if (tempChoice == 'y') {
            settlementCreation();
        } else {
            isMakingSettlement = false;
        }
    }
    return 0;
}

settlementCreation()函数:

void settlementCreation() {
    int tempType{};
    int tempNation{};
    bool isTypeValid = false;
    bool isNationValid = false;
    while (isTypeValid = false) {
        cout << "What type of settlement would you like to create?:";
        cout << "\n     1. Hamlet";
        cout << "\n     2. Village";
        cout << "\n     3. Town";
        cout << "\n     4. City\n";
        cin >> tempType;
        if (tempType >= 1 && tempType <= 4) {
            isTypeValid = true;
        } else {
            cout << " is an invalid choice, please select a valid choice.";
        }
        cout << "\n\n";
    }
    while (isNationValid = false) {
        cout << "What nation would you like your settlement to be in?: ";
        cout << "\n     1. Latin";
        cout << "\n     2. German";
        cout << "\n     3. Eastern\n";
        cin >> tempNation;
        if (tempNation >= 1 && tempNation <= 3) {
            isNationValid = true;
        } else {
            cout << " is an invalid choice, please select a valid choice.";
        }
        cout << "\n\n";
    }
    Settlement objSettlement(tempType,tempNation);
}

因此,该程序应该允许用户选择国家和结算类型,然后再重定向到Settlement对象构造函数以创建对象的objSettlement实例。 但是,通常的结果只是以下情况的无限循环: “创建结算?(是/否):” 没有响应,我试图关闭程序或转到“ settlementCreation()”函数。

1 个答案:

答案 0 :(得分:6)

while (isMakingSettlement = true) {

如果isMakingSettlementtrue,则不会检查。它设置 isMakingSettlementtrue!这意味着while循环中的检查总是看到true,因此永远不会停止运转。

使用while (isMakingSettlement == true)

(或while (isMakingSettlement)while (true == isMakingSettlement);都很好,这是一种样式选择,though the last would have helped you catch this bug!)。

类似地,对于所有其他while循环。


假设您已解决上述问题,那么下一个问题将在这里

bool isTypeValid = false;
bool isNationValid = false;
while (isTypeValid == false) { // once corrected
    // ... never get here!
while (isNationValid == false) { // once corrected
    // ... never get here!

您始终将这些bool设置为false,因此这些循环永远不会执行。