Search code examples
c++if-statementreturnprogram-entry-pointvoid

How to make void not return when answer == true


I made this program and when I type "yes" it should end my program instead it's waiting for me to say something more and then it comes with my void nottrue(); what should I do to avoid this? Here's my code

#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;
}

Solution

  • While return nottrue() works , it's nothing but a function call, because both caller and called function have no returned value. You don't alter flow in any way. You have to use results returned by function for control flow. E.g.

    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;
    }
    

    Also there is predefined exit() function to exit program.