Close a Repeating Main Function

Jan 31, 2013 at 9:39pm
Hi all. I'm very new to C++, really just been learning the past two days. I'm going through the tutorial on www.learncpp.com. I made a variation of his simple Calculator program from the tutorial, only mine uses a header file to organize all my functions. My problem is that I want my Calculator program to repeat the main function, but I also want to be able to close it from the console (maybe by typing "Exit" or something like that). I read in another forum that I can put "return main();" at the end of my main function to get it to repeat, but how do I get it to close without closing the cmd console?

Here is my code for my main.cpp.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <string>
#include "math.h"
using namespace std;

void PrintResults(int nResult);

int main()
{
	int nInput1 = GetUserInput();
	char chOperator = GetMathematicalOperation();
	int nInput2 = GetUserInput();
	int nResult = CalculateResults(nInput1, chOperator, nInput2);
	PrintResults(nResult);
	return main();
}


Thanks!
Jan 31, 2013 at 10:32pm
Never call the main function directly like that, it will cause problems.

Keep everything in a while loop and ask for user input at the end of it to see if they want to continue.

1
2
3
4
5
6
7
8
9
10
11
12
 
while(Running)
{
	// Do stuff

	char tmp;
	cout << "Do you want to quit? (Y/N)" << endl;
	cin >> tmp;

	if(tmp == 'Y')
		Running = false;
}
Jan 31, 2013 at 10:35pm
I read in another forum that I can put "return main();" at the end of my main function

You cannot. The standard forbids you from calling main.

Jan 31, 2013 at 10:46pm
What you need is a loop.

C++ has various different loop constructs - while, do-while, for.

Check out the while loop, which goes along the lines,

1
2
3
4
5
while (<condition>)
{
  ... do stuff

}


This repeatedly does stuff until the <condition> in the while statement evaluates as true.

So using a while loop, your condition could be a simple bool called keepLooping, for example, which you set = true if the user enters "exit" to a prompt within the loop.

As an aside - calling a function from within itself, for example main() from within main(), is called recursion and is not the way to perform simple loops. You can read up on recursion if you want, but I suspect it's a topic for the future.

Have a go at the loop and let us know how you go!

Oh, and the cmd console will close if you exit the program. If you want the console to hang around so you can see any results before it closes, you can add a final call to a read-line function, such as getch() or read from cin - anything that requires the user to provide input and so pauses execution.

Cheers,
Jim
Jan 31, 2013 at 11:21pm
Not to make you look bad, Jim, but:
This repeatedly does stuff until the <condition> in the while statement evaluates as true.


This repeatedly does stuff while the <condition> in the while statement evaluates as true.

(:
Jan 31, 2013 at 11:22pm
Doh! :-)
Jan 31, 2013 at 11:25pm
Sorry, lmao. Had a few to drink. And when I read your post, I read it as "Until the condition is true".

And AeneasDaedri seems new to C++.
Jan 31, 2013 at 11:28pm
I can't believe I did that - even my description of keepLooping is the wrong way round!

It's good to point these things out when we're trying to teach beginners - we don't want to go confusing them ;-)
Jan 31, 2013 at 11:50pm
ahaha! I never noticed the keepLooping one! lol!!

Few drinks and I'm acting clever without reading the rest! ahaha. And yeah, It's probably best not to give new C++'ers the opposite of what they need!
Feb 1, 2013 at 12:34am
Okay, I guess I'm confused as to where to put the "while" function, because no matter what I do I get a "expected unqualified-id before 'while'" and "'Running' was not declared in this scope".

Does the while function go outside the main, in the main or what?

(And yes, I'm very very new to this.)
Feb 1, 2013 at 12:37am
I think you've declared "Running" within the loop?

1
2
3
4
5
6
7
8
9
10
11
12
13
int main()
{
    bool running = true;

    while( running )
    {
        //code...

        //user input. If user wants to exit - running = false.
    }

    return 0;
}
Last edited on Feb 1, 2013 at 12:38am
Feb 1, 2013 at 12:41am
It goes inside the main() function's body ...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
int main()
{
  bool Running = true; // You have to declare variables before you use them.
                       // Also provide a default value of true, so the loop runs at least once

  while(Running)
  {
     // Your original code, minus the call to main()

     // Ask user whether to exit
     Running = false; // Loop will terminate
  }
  // End while loop

  // Execution continues here after the loop terminates
}


The while isn't a function, it's a built-in statement.

Cheers,
Jim
Feb 1, 2013 at 12:55am
return 0;! Jim! lol.
Feb 1, 2013 at 1:11am
Ohhh ok I feel like an idiot now. That was easy. Thanks guys!

Also, since C++ is a cap sensitive language, if I put "Do you want to quit? (Y/N)" with capital letters, would I have to enter a capital letter for it to recognize the input?

Thanks again for the help!
Feb 1, 2013 at 1:16am
Yes. You can convert the character to upper/lowercase if you want to make sure it is a certain way though.
Feb 1, 2013 at 1:25am
The text you display in the prompt has no effect on the recognized input - they're not linked in any way logically in the code.

If you refer to the code posted by James2250 ..

1
2
3
4
5
6
7
8
9
10
11
while(Running)
{
	// Do stuff

	char tmp;
	cout << "Do you want to quit? (Y/N)" << endl;
	cin >> tmp;

	if(tmp == 'Y')
		Running = false;
}


Line 9 is where you are requiring an uppercase 'Y' to be entered.
You can check for a lowercase 'y' instead or as well if you wanted ...

 
if (tmp == 'Y' || tmp == 'y')


Or you could convert the input to lowercase using the standard tolower() function and just check against 'y', which covers both upper and lower.

 
if (tolower(tmp) == 'y')


Cheers,
Jim
Feb 1, 2013 at 1:27am
Ok cool. I just set the parameters to accept with upper or lowercase :)
Topic archived. No new replies allowed.