密码统计帮助

时间:2012-04-02 01:30:40

标签: c++ loops passwords

void getPassword()
{
  while (true)
  {
    string password;
    cout << "Enter the password: ";
    getline(cin, password);

  if (password == "123456") break;
  cout << "INVALID. ";
  } // while
} // getPassword 



int main()
{
  getPassword();

  double P;
  double r;
  double N = 360;
  double rate; 


  cout << "What's the mortgage amount? ";
  cin >> P;
  cin.ignore(1000, 10);  

  cout << "What's the annual interest rate? ";
  cin >> r;
  cin.ignore(1000, 10); 

  rate = r / 100 / 12; 

  // (p * (1 + r)n * r) / ((1 + r)n - 1)
  double M = P * ((pow))(1 + rate, N) * rate / (((pow))(1 + rate, N) -1);

  cout.setf(ios::fixed|ios::showpoint); 
  cout << setprecision(2);

  cout << "Principal = $" << P <<  endl;

  cout.unsetf(ios::fixed|ios::showpoint);
  cout << setprecision(6); // resets precision to its default 
  cout << "Interest Rate = " << r << "%" << endl; 
  cout << "Amortization Period = " << N / 12 << " years" << endl;

  cout << "The monthly payment = $" << M << endl;


  ofstream fout;
  fout.open("mortgages.txt", ios::app);
  if (!fout.good()) throw "I/O error";
  fout.setf(ios::fixed|ios::showpoint); 
  fout << setprecision(2);

  fout << "Principal = $" << P <<  endl;

  fout.unsetf(ios::fixed|ios::showpoint);
  fout << setprecision(6); // resets precision to its default 
  fout << "Interest Rate = " << r << "%" << endl; 
  fout << "Amortization Period = " << N / 12 << " years" << endl;

  fout << "The monthly payment = $" << M << endl;
  fout.close(); 

  return 0;
} 

什么人?我有一个comsc的家庭作业,我在上一个节目中遇到了障碍。我试图做的是将此程序的用户限制为3次无效的密码尝试。我是否需要将其更改为返回值的子程序,还是可以在不执行此操作的情况下完成此操作?任何帮助将不胜感激!!

1 个答案:

答案 0 :(得分:3)

最简单的方法是更改​​getPassword,使其返回bool,表示用户是否输入了正确的密码。然后,而不是while (true),而不是for (int i = 0; i < 3; ++i) ...而不是breakreturn true。循环之后,return false因为他们进行了3轮而没有输入正确的密码。

在程序的其余部分,而不是仅仅调用getPassword,检查其返回值。如果为false,则输出错误消息并退出。

类似的东西:

bool checkPassword() {  // renaming this, since it doesn't just *get* a password
    for (int i = 0; i < 3; ++i) {
        string password;
        std::cout << "Enter password: " << std::flush;
        std::getline(std::cin, password);
        if (password == "123456") return true;
        std::cout << "INVALID.\n";
    }
    std::cout << "Maximum attempts exceeded.\n";
    return false;
}

int main() {
    if (!checkPassword()) {
        return 1;
    }

    ... rest of main() here ...
}