程序应该提示用户输入一个5个字母的字符串。如果字符串不是5个字符,则显示错误消息。如果密码是5个字符,则使用while循环通过反转字符串中字符的顺序并从每个字符中减去15来生成密码,从而在新的字符串变量中生成密码。只能使用iostream,iomanip,cmath,字符串库。
我对这个问题唯一的问题是构造while循环,将原始字符串反转为新字符串,并从反向字符串中的每个字符中减去15以构造新密码。
#include <iostream>
#include <string>
#include <iomanip>
#include <cmath>
using namespace std;
int main()
{
// declaring/initializing variables
string password, newPass;
int index;
// greeting message
cout << "-------------------------------" << endl
<< " John Password Generator " << endl
<< "-------------------------------" << endl;
// asking user for input
cout << "Please enter a 5 character word which will be used to generate a password: " << endl;
getline(cin,password);
// condition if password is less than or greather than 5 characters
if (password.length() != 5)
{
cout << "Sorry, but that is not a 5 character string. Program will terminate. \n\n"
<< "Thank you for using John Password Generator program.\n\n";
}
else
{
index = 0;
password = string(password.rbegin(), password.rend());
while (index < password.length())
{
index++;
}
}
return 0;
}
答案 0 :(得分:1)
您需要遍历password
中的每个元素,并从中减去15:
index = 0;
password = string(password.rbegin(), password.rend());
while (index < password.length())
{
// Minus 15 from each letter in password
password[index] -= 15;
// We've finished with this letter, so increment the index
index++;
}
当然,如果您不需要使用while
循环,则可以使用标准库;具体来说:std::transform
转换string
中的每个字母:
else
{
// Start from the end of the string, and deduct 15 from the character and append it to the start of the string
std::transform(password.rbegin(), password.rend(), password.begin(), [](unsigned char c){ return c - 15; });
}