我需要通过暴力破解给定的密码。所以我决定使用返回 string
string bruteforce(string password, string forcedPassword)
{
if (password.length() == forcedPassword.length())
{
if (password == forcedPassword)
{
return forcedPassword;
}
// What can I do here to return nothing and continue from the previous step?
}
for (int j = 32; j <= 126; j++)
{
forcedPassword += char(j);
bruteforce(password, forcedPassword);
}
}
int main()
{
...
cin >> password;
cout << bruteforce(password, "");
...
}
问题是当我得到 password.length() == forcedPassword.length()
但它们不一样。我只需要在没有任何返回值的情况下退出递归的最后一步。有什么办法可以做到吗?
最佳答案
假设密码非空(否则使用optional
),你可以这样写:
std::string bruteforce(const std::string& password, const std::string& forcedPassword)
{
if (password.length() == forcedPassword.length())
{
if (password == forcedPassword)
{
return forcedPassword;
}
return "";
}
for (int j = 32; j <= 126; j++)
{
auto res = bruteforce(password, forcedPassword + char(j));
if (!res.empty()) {
return res;
}
}
return "";
}
关于c++ - 特殊情况不返回的递归返回函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48346951/