Running Functions again in C++

G

gilly_54

Guest
Ok so I'm new to C++ and I'm working well through it, enough to make my own calculator and other useful little trinkets. Now what I'm finding annoying is having to reopen my program to use it again. Is there a way to start the main function again without having to close and reopen the program? For example in my calculator I named the main function: main() [thank you captain obvious :p], is there a way to run it again after the program has done what it has to?
 
Last edited:
i don't know c++, but can't you just have another method running your main method, so that when the main method has finished executing, it goes back to the other method, which starts it again. basically a glorified loop.
 
You're probably asking for what is a "Do ... While" loop (explained just below), or a "While" loop (explained even further below.)

Here's a really basic layout of the syntax for it:
Code:
[FONT=Courier New]do {

DO_THIS

} while (this)[/FONT]
Here's a small example using the syntax:

Code:
[FONT=Courier New]#include <iostream>
using namespace std;

void Greet(void); //function prototype

int main()
{
 int choice;
 
 /*BEGINNING OF THE LOOP*/
 do {

  cout << "What would you like to do?" << endl;
  cout << "(1) - GREET ME\n";
  cout << "(2) - EXIT PROGRAM\n";
  cin >> choice; //get choice from user

  switch (choice)
  {
    case 1: {  //if user chooses 1
    Greet();
    break; }

    case 2: {  //if user chooses 2
    cout << "\nPress ENTER to exit.\n";
    cin.ignore();
    cin.get();
    return 0; }

    default: { //if user chooses neither 1 nor 2
    cout << "\nINVALID CHOICE\n\n";
    break; }
  }
 

 } while((choice!=1)||(choice!=2)); //keeps doing it while choice isn't 1 or 2
 /*END OF THE LOOP*/ 


cin.get();
return 0;
}


void Greet(void) //function definition
{
 cout << "\nGreetings!\n\n";
}
[/FONT]


_________________________________________

There's also a "While" loop.

Here's the basic syntax layout:

Code:
While (this)
{
DO THIS
}

So how is a "While" loop different?

It is different because it only performs the actions IF IT IS TRUE; If it is NOT true, it NEVER performs the actions.

A "Do .. While" loop always performs the actions AT LEAST ONCE, then after the actions are complete, it checks if the "While" statement is true; if it is not true, it does nothing.

Finally, here's an example of the "While" loop in action:

Code:
#include <iostream>
using namespace std;

int main()
{
   char choice = 'y';
   
   while (choice == 'y')
   {
   cout << "Continue? ('y' if yes): ";
   cin >> choice;
   }

cout << "\nOk then, bye!  Press 'ENTER' to exit.";
cin.ignore();
cin.get();
return 0;
}

Hope this helps!

 
If you are new to c++ then I think this would be an excellent time to learn classes. Wrap up all your calculator code into a class. Create the class outside of a loop and run the calculator inside of a loop.

example:

Code:
MyCalcClass Calculator;

while( Calculator.IsOpen() )
{
   Calculator.go()
}
 
Yea I am quite new to C++, I will post my source code of my most recent calculator, seems to work fine, can you tell me how to implement the things you told me here into it?:
Code:
// gillyscalculatorv2.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <cstring>
#include <cmath>

using namespace std;

int main()
{
	double num1, num2, ans;
	char sign;

	cout<<"Enter a calculation in this format: Number(+,-,*,/)Number"<<endl;
	
	cin>>num1>>sign>>num2;
	cin.ignore();
	
	if (sign == '+'){
		ans=num1+num2;
		cout<<ans<<endl;
		main();
	}

	if (sign == '-'){
		ans=num1-num2;
		cout<<ans<<endl;
		main();
	}

	if(sign == '*'){
		ans=num1*num2;
		cout<<ans<<endl;
		main();
	}

	if(sign == '/'){
		if(num2 == 0){
			cerr<<"Can't divide by zero!"<<endl;
			main();
		}
		else{
			ans=num1/num2;
			cout<<ans<<endl;
			main();
		}
	}

	if(sign != '+'||'-'||'*'||'/'){
		cerr<<"Bad input: The operator("<<sign<<")you entered is invalid."<<endl;
		main();
		
	}
}
Lol, looks really simple I know...
 
Yea I am quite new to C++, I will post my source code of my most recent calculator, seems to work fine, can you tell me how to implement the things you told me here into it?:

Well this does not incorporate the suggestion to create a class for the
calculator (it is total overkill in this case, IMO. You should first try to get
a solid understanding of regular C before moving on to C++)

You should also check your coding style. I myself prefer the linux coding
guidelines, but that is a matter of preference. Just use something that makes
the code more readable :)

I modified the code so that the calculator is a function calc(), which
gets called repeatedly until you try a divide-by-zero.

Code:
// gillyscalculatorv2.cpp : Defines the entry point for the console application.
//
#include <iostream>
#include <cstring>
#include <cmath>

using namespace std;

int calc(void)
{
	double num1, num2, ans;
	char sign;

	cout << "Enter a calculation in this format: Number(+,-,*,/)Number" << endl;
	
	cin >> num1 >> sign >> num2;
	cin.ignore();
	
	if (sign == '+') {
		ans = num1 + num2;
	} else if (sign == '-') {
		ans = num1 - num2;
	} else if (sign == '*') {
		ans = num1 * num2;
	} else if (sign == '/') {
		  if (num2 == 0) {
			cerr << "Can't divide by zero!" << endl;
			return 0;
		} else {
			ans = num1 / num2;
		}
	} else {
		cerr << "Bad input: The operator (" << sign << ") you entered is invalid." << endl;
		return 1;
	}
        cout << ans << endl;
        return 1;
}

int main(int argc, char **argv)
{
      while (calc())
          ;
      return 0;
}
It's not compile or run-tested, but you should be able to get the idea :)
 
I compiled your code, it runs perfectly, I just modified some things so that the calculator runs again when I divide by zero.
so I understand "return 1" is the same as putting in "main();" again in my code. I'm guessing that's more efficient. And I completely forgot about my else if, I was wondering why another program of mine would never work (encryptor...shh :P)
 
the "return 1" lets the while() loop continue (the ; in there is just an
empty statement). As long as the function calc() returns anything but zero
the while() loop will "loop" again. If it returns zero, the loop ends.

As I stated, this is basic C, and you should get a good grasp of it first.
(I suggest you borrow "The C programming language" by Kernighan/Ritchie from your local library. It's an excellent book)
 
the "return 1" lets the while() loop continue (the ; in there is just an empty statement)

As far as I know, with the MS C++ compiler you don't need the stranded ";", as it will know that already, but I haven't programmed anything in months :(:cry: :cry: so I could be mistaken
 
The ; IS required in this case, otherwise the compiler would assume the 'return 0'
belongs to the while().
 
The ; IS required in this case, otherwise the compiler would assume the 'return 0'
belongs to the while().

yes but it doesn't need a newline. I've never liked hanging ; in my code. if the reader can't understand why there's a ; when there normally isn't then that's not my problem.
 
Yeah the newline ist required; but I like this particular coding style. Makes it
immediately obvious that the loop was meant to be empty without having to
parse called functions/context.
 
The ; IS required in this case, otherwise the compiler would assume the 'return 0'
belongs to the while().

Ahhh see I would have done:

Code:
int main(int argc, char **argv)
{
      while (calc()) {}
      return 0;
}

Instead of:

Code:
int main(int argc, char **argv)
{
      while (calc())
          ;
      return 0;
}

Okay so it's been about 8 months since I touched C++, 6 months since C# and 1 year since Java, so my code my be totally wrong :cry:
 
Back
Top