SlothGamer
SlothGamer

Reputation: 84

How do I make my code Repeat instead of ending in c++?

The code tells you if it's a prime or not, I've Tried Everything I could find, like a 'do while' loop and others It just won't work my code is if anyone could help.

though it is probably me putting it in the wrong place so if anyone could put my code in the way to do it that would help alot.

#include <iostream>
using namespace std;

int main()
{
    {
        int n, i, m = 0, flag = 0;
        cout << "(press 'x' to exit) Enter the Number to check if It's a prime Number or not: ";
        cin >> n;

        m = n / 2;
        for (i = 2; i <= m; i++) {
            if (n % i == 0)
            {
                cout << "That's not a prime number." << endl;
                flag = 1;
                break;
            }
        }
        if (flag == 0)
            cout << "That's a prime number." << endl;
    }
}

Upvotes: 1

Views: 531

Answers (1)

Veda
Veda

Reputation: 2073

Put a while(true) around everything. I see you already got the {} for that:

int main()
{
    while (true) {
        int n, i, m = 0, flag = 0;

If you do it this way it will endlessly continue asking. Ctrl+C will end the program.

If you want to have the press x to exit working, something like this would work:

int main()
{
    while (true) {
        string s;
        int n, i, m = 0, flag = 0;
        cout << "(press 'x' to exit) Enter the Number to check if It's a prime Number or not: ";
        cin >> s;

        if (s == "x")
            break;

        n = atoi( s.c_str() );

        m = n / 2;

Upvotes: 2

Related Questions