我编写了一个程序,为用户提供一些有关减肥的信息,以及如何根据我要求用户输入的一些信息达到特定目标。我正处于可以开始实现函数以使主函数更好的阶段,但我不想继续,直到我解决了这个问题。
它在Visual Studios中运行得很好,完美地输出了最后一部分,但是如果我尝试在build文件夹中找到Debug或Release的.exe,它就会在它告诉用户信息之前退出程序想。
我不确定为什么会发生这种情况,因为它不会给我任何构建错误或编译器错误。这是.exe跳过的代码:
cout << "Choose your rate at which you'd like to meet your goal! " <<
"\n 1. Fast\n 2. Medium\n 3. Slow" << endl;
int uRate;
cin >> uRate;
//This bit of code it executes, and the user inputs their rate, which
//assigns the value to the switch statement for it to determine it's case.
double time = uWeight - uGoalWeight;
double fastrate = (uWeight * 0.01);
double mediumrate = (uWeight * 0.0075);
double slowrate = (uWeight * 0.005);
int newTime;
switch (uRate) {
case 1:
newTime = time / fastrate;
cout << "Your time in weeks to reach your goal is : " << newTime << " weeks." << endl;
cout << "You'd have to lose " << fastrate << " lbs per week to meet this goal!" << endl;
cout << "Remember, your optimal goal weight would be: "
<< uGoalWeight << " lbs!" << endl;
break;
case 2:
newTime = time / mediumrate;
cout << "Your time in weeks to reach your goal is : " << newTime << " weeks." << endl;
cout << "You'd have to lose " << mediumrate << " lbs per week to meet this goal!" << endl;
cout << "Remember, your optimal goal weight would be: "
<< uGoalWeight << " lbs!" << endl;
break;
case 3:
newTime = time / slowrate;
cout << "Your time in weeks to reach your goal is : " << newTime << " weeks." << endl;
cout << "You'd have to lose " << slowrate << " lbs per week to meet this goal!" << endl;
cout << "Remember, your optimal goal weight would be: "
<< uGoalWeight << " lbs!" << endl;
break;
基本上,这是一些代码,它不会在release / debug .exe文件中显示。只要在VS2019发布时调试或运行,其他所有工作都可以正常工作。我需要显示此信息,因为它是应用程序编码的全部原因。
OP说
你没事。我通过在switch语句的末尾添加系统(“pause”)来修复它。
在drescherjm提供的链接SO: How to stop C++ console application from exiting immediately?中,大约有50%的答案得到了类似的提示。
我相信system("pause");
是一个糟糕的解决方案,只是在应用程序结束时等待用户确认。 - 它可能使应用程序易受攻击。
谷歌搜索我发现例如ENV33-C. Do not call system()说
使用
system()
函数可能导致可利用的vulnerabilities,在最坏的情况下允许执行任意系统命令。调用system()的风险较高的情况包括:
- 传递源自受污染源的未经过清理或未正确清理的命令字符串时
- 如果指定的命令没有路径名,则攻击者可以访问命令处理器路径名解析机制
- 如果指定了可执行文件的相对路径,则攻击者可以访问当前工作目录的控制权
- 如果指定的可执行程序可能被攻击者欺骗
不要通过
system()
或等效函数调用命令处理器来执行命令。
使用一些语句和C ++ std库实际上很容易实现在应用程序结束时等待用户确认:
#include <iostream>
#include <string>
void pause()
{
std::cout << "Press [ENTER] to continue...";
std::string input; std::getline(std::cin, input);
}
int main()
{
std::cout << "Hello World.\n";
pause();
return 0;
}
输出:
Hello World.
Press [ENTER] to continue...
顺便说一句。这个解决方案更加便携,因为它不依赖于标准库以外的任何东西。
回到过去的日子,控制台程序在哪里通常的计算机工作方式,你可以看到
Press any key to continue...
经常。一个频繁重复虽然蹩脚的笑话是:
“程序说我可以按任意键。我按住Shift和Alt并按Ctrl键很多次但没有任何事情发生。”