Reputation: 10686
How do you stop the code from running in C++? I have the code
#include <iostream>
#include <cmath>
using namespace std;
int main() {
int total, sub, subc;
cout << "What number would you like to start with? ";
cin >> total;
cout << "Enter in a number, 1 or 2, to subtract";
cin >> sub;
if (sub == 1) {
total--;
subc++;
cout << "You subtracted one";
}
else {
total = total - 2;
subc++;
}
if (sub <= 0)
cout << "YAY!";
}
and i want to insert a thing that just stops the code and exits right after cout << "YAY!"
how do i do that???
Upvotes: 0
Views: 32148
Reputation: 8207
As David Robinson already noted, your example makes no sense, since the program will stop anyway after
cout << "YAY!";
But depending on the scenario, besides break and return, also exit() might help. See the manpage:
http://www.cplusplus.com/reference/cstdlib/exit/
Upvotes: 0
Reputation: 97918
try:
char c;
cin >> c;
This will wait until you hit enter before exiting.
or you can do:
#include <stdlib.h>
system("pause");
Upvotes: 1
Reputation: 78590
A return statement will end the main
function and therefore the program:
return 0;
ETA: Though as @Mysticial notes, this program will indeed end right after the cout << "YAY!"
line.
ETA: If you are in fact working within a while loop, the best way to leave the loop would be to use a break
statement:
#include <iostream>
#include <cmath>
using namespace std;
int main() {
int total, sub, subc;
cout << "What number would you like to start with? ";
cin >> total;
while (1) {
cout << "Enter in a number, 1 or 2, to subtract";
cin >> sub;
if (sub == 1) {
total--;
subc++;
cout << "You subtracted one";
}
else {
total = total - 2;
subc++;
}
if (sub <= 0) {
cout << "YAY!";
break;
}
}
}
Upvotes: 4