Hi, I am a beginner at C++ (only can write basic console programs ATM), and I was wondering what the best way to shut the console down from the program is?
What I'm looking for is a way to force the program to close from outside the main function. The main function is a void function by the way, in case that makes a difference. I was thinking there would be a way to go to the end of the main function, like in the goto control structure. But that probably isn't the case... :P
I've heard that using system("...") is slow and insecure, so I thought maybe there is another, better way of doing it.
I know there was a system("...") way of doing it, I just can't remember what it was, or seem to find it online.
main should return an int. Always. void main() is nonstandard and weird. It should be int main()
If you want to exit the program from anywhere, there's a function called exit() which does just that:
1 2 3 4 5 6 7 8 9 10
void afunc()
{
exit(0); // exits the program with code 0 (like returning 0 from main)
}
int main()
{
afunc(); // exits
cout << "this will not be printed";
}
Of course there are pros and cons to this, and it's generally considered "cleaner" or "more graceful" to have your program flow return back to main and have main exit normally. But it all depends.