I have a snippet of code that's 37 lines long, I can't, for the life of me, seem to get it working. It compiles fine, no errors, I've had 2 friends run through it and nothing, is it just an issue with my compiler(CodeBlocks)? Long story short I really just need this code to be able to take a yes or no answer, help me out? Thanks in advance.

#include<iostream>
#include<windows.h>
#include<conio.h>
#include<strings.h>

using namespace std;

int main();
void repeat();

string s1;
string s2;
string s3;

int main()
{
        repeat();
}

void repeat()
{
    string s3="n";
    cout << "Would you like to perform another operation?\n";
    cin >> s3;
    if((s3=="Y" || "y"))
    {
        main();
    }
    if((s3=="N" || "n" || "no" || "No"))
    {
        exit(0);
    }
    else
    {
        exit(0);
    }
}

Recommended Answers

All 19 Replies

The if statements still need to compare to s3:

if((s3=="Y" || s3=="y"))
{
   ... //etc
}

>> if((s3=="Y" || "y"))]

You want if(s3 == "Y" || s3 == "y") or if(s3.find("yY") != string::npos) or if(tolower(s3[0]) == 'y')

You want if(s3 == "Y" || s3 == "y")

I tried this already, the other 2 I haven't really learned yet, any luck with compiling and testing the functionality of it?

line 27 is problematic because main variable doesn't exist there. What you want is something like this:

#include <iostream>
using namespace std;

void doOperation(){ /* do nothing for now */ }

int main(){
 bool shouldContinue = true;
 while(shouldContinue){
     doOperation();
     cout << "Repeat again<y/n> : ";
     char ch = 0;
     cin >> ch;
     if(ch == 'y' || ch == 'Y') shouldContinue = true;
     else shouldContinue = false;
 }
}

Never never NEVER call main() . NEVER! It's an entry point to your program not a normal function.

Why call exit() (twice) when all you need to do is return?

The if statements still need to compare to s3:
C++ Syntax (Toggle Plain Text)
if((s3=="Y" || s3=="y"))
{
... //etc
}

See I thought this was the correct way? It seems to not work with this current variation, and to answer questions, I have exit where I want to close the program, and I have main(); just because I needed a short and sweet way to text this.

Is it possible to get it up and running without a Boolean value?

Everything is possible. Reagrdless of how quick-and-dirty you're trying to be, take good advice when it's given. main should almost always be declared as:

int main (int argc, char *argv[])
{
    ...
}

And there's almost never a reason to call it from inside itself or any other part of your program. When you absolutely need to call main() yourself, you'll know. Until then, just don't do it.

I don't know why you'd want a user-input-controlled loop to be implemented using recursion (the function calling itself over again if the user wants to repeat), but that's not the aspect that's not working. At least consider having repeat() call itself instead of calling main().

Also, the assumption should be that exit() is called only from main() (as a replacement for a simple "return" statement). Someone reading your code should expect all function calls to return execution back to their caller, and ultimately to main(), which will call exit() or return as appropriate to end your program.

If you've fixed your if() expressions and your code still doesn't work, please post the revised code so we can see what else might have gone wrong.

Thanks.

A couple nitpicks:

main should almost always be declared as:

int main (int argc, char *argv[])
{
    ...
}

Not really. main should almost always be declared as int main(void) . Your version only needs to be used when you need command line parameters.

And there's almost never a reason to call it from inside itself or any other part of your program. When you absolutely need to call main() yourself, you'll know. Until then, just don't do it.

No, just don't do it. There's never a need to call main() . If you need to start from the top in main() recursively, create another function that main() calls and put all the functionality into that function.

Also, the assumption should be that exit() is called only from main() (as a replacement for a simple "return" statement). Someone reading your code should expect all function calls to return execution back to their caller, and ultimately to main(), which will call exit() or return as appropriate to end your program.

IMO, and this is just an opinion, the only time you should use exit() is when you have an error deep enough in your calling structure that getting back to main() is problematic. Like in a 4th level function that can't find a required file, and returning with an error up through the 2 other functions makes the code too messy. From main() itself, why call a function? Just return. It's simpler with fewer resources.

My 2 cents...

>>

IMO, and this is just an opinion, the only time you should use exit() is when you have an error deep enough in your calling structure that getting back to main() is problematic. Like in a 4th level function that can't find a required file, and returning with an error up through the 2 other functions makes the code too messy. From main() itself, why call a function? Just return. It's simpler with fewer resources.

My 2 cents...

Usually, its rare to have such deep structures, at least for me since I never had the need for one. I would advice one to only use exit when the program cannot proceed any further because of a internal error like file not existing and such.

Yeah sorry about the rough-draft, it's not even my full program its just a little snippet that i threw together because the original program wasn't working, I never call main, I promise, ha. Anyway, given that here is the cleaned up code, still not working. By the way I'm a huge newbie, if you couldn't already tell.

#include<iostream>
#include<windows.h>
#include<conio.h>
#include<strings.h>

using namespace std;

int main();
void repeat();
void worked();

string s1;
string s2;
string s3;

int main()
{
        repeat();
}

void repeat()
{
    string s3="n";
    cout << "Would you like to perform another operation?\n";
    cin >> s3;
    if((s3=="Y" || "y"))
    {
        worked();
    }
    if((s3=="N" || "n" || "no" || "No"));
}

void worked()
{
    cout << "Hey guys, it worked!";
    Sleep(5000);
}
#include<iostream>
#include<windows.h>
#include<conio.h>
#include<strings.h>

using namespace std;

int main();
void repeat();
void worked();

string s1;
string s2;
string s3;

int main()
{
        repeat();
}

void repeat()
{
    string s3="n";
    cout << "Would you like to perform another operation?\n";
    cin >> s3;
    if((s3=="Y" || "y"))
    {
        worked();
    }
    if((s3=="N" || "n" || "no" || "No"));
}

void worked()
{
    cout << "Hey guys, it worked!";
    Sleep(5000);
}

Who reviewed your code and told you it would work? I see several problems up front:

1. Half your inclusions are not necessary. The only inclusions you need are Iostream and strings.h.

2. You have a prototype of your main function, which is completely unnecessary. Prototypes exist so that if you call a function before it is actually defined in your code, your compiler knows it exists and won't throw an exception at you. Since nothing is called before Main, it's just a waste of space. Your main function also doesn't have a return call.

3.Your "Repeat" function isn't actually repeating, since it's not looped or recursive.

4.

if((s3=="Y" || "y"))

still needs to be changed to

if((s3=="Y") ||(s3== "y"))

5. Your second if statement does nothing. It checks for a condition but nothing is done if the condition is true.

6. Usage of the "sleep" function is not necessary. I'm not even completely sure what you're trying to do with it.

7. You declare 2 strings you don't use.

And this is just the immediately obvious. I'm curious where you're learning C++ from because a lot of this stuff should have been explained to you. There are plenty of excellent books on the market that will teach you this stuff as well. This is a nice list made by the some members of this board.

Yeah, main() should never be called. I'm actually surprised that the compiler didn't yell at you for something like that, in many environments it's not even legal C. You should also not have to prototype main().

Once that code gets fixed, however, you might have problems because I'm not entirely sure if cin strips trailing newline characters.

About the exit() debate, I've had to use exit() a few times, but you'll almost never use it in a simple program. When you start making large programs, however, you'll find usefulness in atexit(), which registers a function to be called during an exit() call. It's also nice to have a catch-all fatal-error handling function that prints a useful message and then quits with status EXIT_FAILURE.

bacareful you had declared s3 twice

Okay so I was just messing around with the code some more and noticed this... If you call the function you are in from itself then it will not see this unless you are inside of main, so my question then becomes, "can you program a recursive function outside of main? I know that calling main is bad but that seems the only way to get it to call recursively".

Thanks in advance

You need to ask the question again. It's confusing.

Certainly, you can write functions that work recursively, yes. Here is your function written in just such a fashion:

#include <iostream>
#include <cctype>

using namespace std;

void repeat();

int main()
{
        repeat();
}

void repeat()
{
    char s3='n';
    cout << "Would you like to perform another operation? (Y/N)" << endl;
    cin >> s3;
    s3 = toupper(s3);
    if (s3=='Y')
    {
        repeat();
    }
}

Now, in C++, recursion often gets a bad rap for inefficiency, especially since (by default at least) C++ compilers generally don't perform tail call optimization. But it is perfectly possible to use recursion in this manner, yes.

@Schoil-R-LEA you can do it that way, and yes I've done it that way, but it doesn't really matter because it's pretty much the same as calling main, if it loops enough, it WILL crash the program, that is one fact I do know. But for others I'll post my super revised/full length code, it still won't recognize s2.

#include<iostream>
#include<windows.h>

using namespace std;

double d1;
double d2;
string s1;
string s2;

int main()
{
    do
    {
        cout << "What math operation would you like to perform?\n";
        cin  >> s1;

        if((s1=="Division") || s1==("division") || (s1=="/"))
        {
            cout << "Enter the first number: ";
            cin >> d1;
            cout << "Enter the second number: ";
            cin >> d2;
            double division = (d1 / d2);
            cout << "The answer is: " << division;
            cout << "\n";
            cout << "would you like to do another calculation?";
            cin >> s2;
            break;
        }
        else if((s1=="Addition") || (s1=="addition") || (s1=="+"))
        {
            cout << "Enter the first number: ";
            cin >> d1;
            cout << "Enter the second number: ";
            cin >> d2;
            double addition = (d1 + d2);
            cout << "The answer is: " << addition;
            cout << "\n";
            cout << "would you like to do another calculation?";
            cin >> s2;
            break;
        }
        else if((s1== "Subtraction") || (s1=="subtraction") || (s1=="-"))
        {
            cout << "Enter the first number: ";
            cin >> d1;
            cout << "Enter the second number: ";
            cin >> d2;
            double subtraction = (d1 - d2);
            cout << "The answer is: " << subtraction;
            cout << "\n";
            cout << "would you like to do another calculation?";
            cin >> s2;
            break;
        }
        else if((s1== "Multiplication" || s1=="multiplication") || (s1=="*"))
        {
            cout << "Enter the first number: ";
            cin >> d1;
            cout << "Enter the second number: ";
            cin >> d2;
            double multiplication = (d1 * d2);
            cout << "The answer is: " << multiplication;
            cout << "\n";
            cout << "would you like to do another calculation?";
            cin >> s2;
            break;
        }
        else
        {
            cout << "It seems you typed something wrong.\n";
            continue;
        }
    }while(s2== "yes" || "Yes" || "y" || "Y");

    cout << "Thank you for using this calclator..\n";
    cout << "Any key will close this console";
    cin.get();
    cin.get();
    return 0;
}

line 75

@Schoil-R-LEA you can do it that way, and yes I've done it that way, but it doesn't really matter because it's pretty much the same as calling main,

No, it's not at all like calling main() because calling main() is wrong. This has been explained already so it's not at all the same.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.