如何立即停止/结束程序?

时间:2019-12-08 02:42:15

标签: c++ c++11 visual-c++ c++14 c++17

询问用户是否要返回主菜单,如果用户输入n / N,则仅在应立即结束程序时才进入下一个解决方案。下面显示的是我用于程序的代码。当选择“否”时,请帮助我解决如何立即终止程序。非常感谢!

void number()

int b=0;
int groupChoice=0;
float ave[groupChoice];
int trials[groupChoice];
float result,sumRes,dAve;
int sumTry=0;
char choice;

cout << "\nNUMBER OF TRIALS" << endl;
cout << "\nHow many groups? ";
cin >> groupChoice;
for (int j=0;j<groupChoice;j++)
{
    cout << "Average distance for group " << j+1 << ": ";
    cin >> ave[j];
    cout << "No. of trials for group " << j+1 << ": ";
    cin >> trials[j];
}
cout << "\nGroups\t\tAve. Distance(x)\tNo. of trials(w)\tx(w)" << endl;
for (int i=0;i<groupChoice;i++)
{
    result=ave[i]*trials[i];
    cout << "Group " << i + 1 << "\t\t" << ave[i] << "\t\t\t" << trials[i] << "\t\t\t" << result << endl;
    sumTry=sumTry+trials[i];
    sumRes+=result;
}
cout << "\t\t\t\t\tSum = " << sumTry << "\t\tSum = " << sumRes << endl;
dAve = sumRes / sumTry;
cout << "Distance Average is " << dAve << endl << endl;
b=0;
while(b==0)
{
    cout << "Would you like to return to main menu? [Y or N]: ";
    cin >> choice;
    if (choice=='Y'||choice=='y')
    {
        b++;
        system("cls");
        a=0;
        main();
    }
    else if (choice=='N'||choice=='n')
    {
        b++;
        break;
    }
}

2 个答案:

答案 0 :(得分:1)

您可以通过以下方式终止程序

void std::exit( int exit_code );

例如

std::exit(EXIT_SUCCESS);

https://en.cppreference.com/w/cpp/utility/program/exit

答案 1 :(得分:0)

有两个选择

使用

std::exit(<exit_code>);

std::_Exit(<exit_code>);

更多信息: https://en.cppreference.com/w/c/program/_Exit