【问题标题】:How to make void not return when answer == true [closed]当答案== true时如何使void不返回[关闭]
【发布时间】:2021-04-04 01:21:15
【问题描述】:

我制作了这个程序,当我输入“yes”时,它应该结束我的程序,而不是等待我说更多内容,然后它带有我的 void nottrue();我应该怎么做才能避免这种情况?这是我的代码

#include <iostream>

using namespace std;

void CharacterWorld();
void nottrue();

int main()
{
    CharacterWorld();
    nottrue();
    return 0;
}

void CharacterWorld()
{
    string CharacterName;
    int CharacterAge;
    string yesorno;
    cout << " Hi, welcome to the Vanish World! " << endl;
    cout << " What's your name champion? " << endl;
    cin >> CharacterName;
    cout << " ...And what's your age? " << endl;
    cin >> CharacterAge;
    cout << " ... So your name is " << CharacterName << " and your age is " << CharacterAge << " Is that right?" << endl;
    cin >> yesorno;
    if (yesorno == "yes")
    {
        cout << " Okey! so let's start your journey champion!" << endl;
    }
    else
    {
        cout << " SO what's your name then ??" << endl;
        return nottrue();
    }
}

void nottrue()
{
    string CharacterName;
    int CharacterAge;
    string yesorno;
    cin >> CharacterName;
    cout << " and what's your age?" << endl;
    cin >> CharacterAge;
    cout << " ...Okey, already. Your name is " << CharacterName << " and your age is " << CharacterAge << endl;
}

【问题讨论】:

  • return nottrue(); 调用 nottrue() 并退出,void 不是一个值,不是任何类型的结果。当然,接下来您会再次致电nottrue()

标签: c++ if-statement return main void


【解决方案1】:

虽然return nottrue() 有效,但它只是一个函数调用,因为调用者和被调用函数都没有返回值。你不会以任何方式改变流量。 您必须将函数返回的结果用于控制流。例如

bool CharacterWorld()
{
    //...
    if (yesorno == "yes")
    {
        cout << " Okey! so let's start your journey champion!" << endl;
        return true;
    }
    else
    {
        cout << " SO what's your name then ??" << endl;
        return false;
    }
}

int main()
{
    if(!CharacterWorld())
        nottrue();
    return 0;
}

还有预定义的exit()函数退出程序。

【讨论】:

    猜你喜欢
    • 2018-04-18
    • 2021-03-14
    • 2013-01-20
    • 2012-02-27
    • 1970-01-01
    • 2016-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多