J
J
Jlad2021-11-02 21:03:42
C++ / C#
Jlad, 2021-11-02 21:03:42

How to prematurely terminate a program in c++?

How to terminate the program if the condition is met? Apologies in advance for th...bad code, and lack of comments.
the code:

#include <iostream>

using namespace std;
int main() {
    int num1, num2;
    string act;

    cout << "Calculator version 0.0.1" << endl;
    while (1 == 1) {
    cout << "Write your first number (or exit to exit programm): " << endl;
    cin >> num1;
    cout << "Write your second number: " << endl;
    cin >> num2;
    cout << "Enter your action (Examples: + / - / * / : / other): " << endl;
    cin >> act;
    if (act == "+") {
        cout << "Answer = " << num1 + num2 << endl;
    }
    if (act == "-") {
        cout << "Answer = " << num1 - num2 << endl;
    }
    if (act == "*") {
        cout << "Answer = " << num1 * num2 << endl;
    }
    if (act == ":") {
        cout << "Answer = " << num1 / num2 << endl;
    }
    if (act == "other") {
        string act2;
        cout << "Other operations (Example: remainder of the division (RoD)): " << endl;
        cin >> act2;
        if (act2 == "RoD") {
          cout << "Answer = " << num1 % num2 << endl;
        }
    if (act == "exit") {
        return 0;    //место, где я хочу чтобы программа заканчивалась, если условие выполнено
    }
    }
    }
}

Using return 0; the program endlessly prints:
Write your first number (or exit to exit programm):
Write your second number:
Enter your action (Examples: + / - / * / : / other):

Edit: Maybe it's because I'm writing code and compile via replit (online environment)

Answer the question

In order to leave comments, you need to log in

2 answer(s)
O
Ocelot, 2021-11-03
@Ocelot

Look carefully where the block ends, if (act == "other")
if (act == "exit")got inside it, and since. actcannot take on two different values ​​at the same time, the exit condition is never met.

R
Ronald McDonald, 2021-11-02
@Zoominger

insert break instead of return .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question