【问题标题】:How to immediately stop/end the program?如何立即停止/结束程序?
【发布时间】:2019-12-08 02:42:15
【问题描述】:

询问用户是否要返回主菜单,如果用户输入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;
    }
}

【问题讨论】:

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


【解决方案1】:

你可以终止你的程序

void std::exit( int exit_code );

例如

std::exit(EXIT_SUCCESS);

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

【讨论】:

  • 初学者最好考虑一下他们的程序的结构,以便让它从main正常返回。
【解决方案2】:

有两种选择

使用

std::exit(&lt;exit_code&gt;);

std::_Exit(&lt;exit_code&gt;);

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

【讨论】:

  • 使用后者不是一个好主意,因为它不会调用析构函数。
猜你喜欢
  • 2018-01-27
  • 2015-12-04
  • 2014-04-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-25
相关资源
最近更新 更多