简体   繁体   中英

How do I loop back to the beginning in c++

I recently started programming in C++, so for my program I need to loop back to the beginning when the user says yes and end the program when the user says no. I was wondering how would I loop back to the beginning?

#include <iostream>

using namespace std;

int main() {
    int x;
    int y;
    char yes, no, answer;

    {
        cout << "Please enter a number for the x coordinate" << endl;

        cin >> x;

        cout << "Please enter a number for the y coordinate" << endl;

        cin >> y;

        if (x == 0) {
            if (y == 0)
                cout << "you are on the origin" << endl;
            else
                cout << "you are on the y axis" << endl;
        }
        else if (x > 0) {
            if (y == 0)
                cout << "you are on the x coordinate" << endl;
            else if (y > 0)
                cout << "you are in the 1st quadrant" << endl;
            else
                cout << "you are in the 4th qaudrant" << endl;
        }
        else if (x < 0) {
            if (y > 0)
                cout << "you are in the 2nd quadrant" << endl;
            else if (y < 0)
                cout << "you are in the 3rd quadrant" << endl;
        }

        cout << "Do you want to run the program again either types yes or no" << endl;

        cin >> answer;

        if (answer == 'yes' || answer == 'Yes')
            system("pause");
    }
}

You can put the code inside a loop:

while(true) {
     ... (existing code goes here)

     if (answer != 'yes' && answer != 'Yes')
         break;

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM