我试图编写一个程序,将密码限制为三次不正确的尝试,然后在3次错误尝试后退出。这是我到目前为止的代码。我觉得我真的很接近搞清楚但我无法弄清楚该怎么做。
#include <fstream>
#include <iomanip>
#include <iostream>
#include <string>
#include <cmath>
using namespace std;
void getPassword()
{
for(int i = 0; i < 3; i++)
{
string password;
cout << "Enter the password: ";
getline(cin, password);
if (password == "12345") break;
cout << "INVALID. ";
} //for
} // getPassword
int main ()
{
if (!getPassword()) break;
else break;
cout <<endl;
ofstream fout;
fout.open("mort.txt", ios::app);
if (!fout.good()) throw "I/O error";
double p; //Principal/Mortgage Amount
cout << "What's the mortgage amount?";
cin >> p;
cin.ignore (1000, 10);
double r;
cout << "What's the annual interest rate?";
cin >> r ;
cin.ignore (1000, 10);
double a = r / 100;
double i = a / 12;
double n = 30 * 12; //Number of payments per month
double t = (p*(pow (1+i, n))*i) / ((pow(1+i, n)) -1);// monthly payment formula
cout<< fixed;
cout<< setprecision(2);
cout << "Mortgage Amount: "<<"$"<< p <<endl;
cout << "Interest Rate: "<< r <<"%"<<endl;
cout << "Term Years: "<< "30 " << "Years" <<endl;
cout << "Monthly Payment: " <<"$"<< t <<endl;
fout << "Mortgage Amount: "<<"$"<< p <<endl;
fout << "Interest Rate: "<< r <<"%"<<endl;
fout << "Term Years: "<< "30 " << "Years" <<endl;
fout << "Monthly Payment: " <<"$"<< t <<endl;
fout <<endl;
fout.close();
return 0;
}
答案 0 :(得分:5)
而不是使用void函数来获取密码或者返回一个布尔值,如果密码输入正确(在if语句中),则为true;如果3次尝试失败(在循环之后),则为false。然后在你的main函数中处理你需要返回的getPassword。
类似
#include <fstream>
#include <iomanip>
#include <iostream>
#include <string>
using namespace std;
#include <cmath>
bool getPassword()
{
for(int i = 0; i < 3; i++)
{
string password;
cout << "Enter the password: ";
getline(cin, password);
if (password == "12345") return true;
cout << "INVALID. ";
} //for
return false;
} // getPassword
int main ()
{
if (!getPassword()) return 1;
cout <<endl;
ofstream fout;
fout.open("mort.txt", ios::app);
if (!fout.good()) throw "I/O error";
double p; //Principal/Mortgage Amount
cout << "What's the mortgage amount?";
cin >> p;
cin.ignore (1000, 10);
double r;
cout << "What's the annual interest rate?";
cin >> r ;
cin.ignore (1000, 10);
double a = r / 100;
double i = a / 12;
double n = 30 * 12; //Number of payments per month
double t = (p*(pow (1+i, n))*i) / ((pow(1+i, n)) -1);// monthly payment formula
cout<< fixed;
cout<< setprecision(2);
cout << "Mortgage Amount: "<<"$"<< p <<endl;
cout << "Interest Rate: "<< r <<"%"<<endl;
cout << "Term Years: "<< "30 " << "Years" <<endl;
cout << "Monthly Payment: " <<"$"<< t <<endl;
fout << "Mortgage Amount: "<<"$"<< p <<endl;
fout << "Interest Rate: "<< r <<"%"<<endl;
fout << "Term Years: "<< "30 " << "Years" <<endl;
fout << "Monthly Payment: " <<"$"<< t <<endl;
fout <<endl;
fout.close();
return 0;
}