c++ - 如何将 std::cin 作为函数的参数传递?
问题描述
我已经在 stackoverflow 上搜索了答案,但根本没有得到它。一个解释清楚的答案将是惊人的。
这是我的密码验证器的不完整代码。我要求用户输入,然后通过一系列布尔函数运行它来确定它是否符合强密码标准。
如果您发现任何其他错误(我确定存在),请告诉我。谢谢!
#include <iostream>
#include <ctype.h>
#include <cstring>
//DECLARING GLOBAL VARIABLES
bool isLong;
bool hasDigits;
bool hasAlphabets;
bool hasSpecial;
//FUNCTION TO CHECK IF PASSWORD IS LONG ENOUGH
bool checklen(std::string x)
{
if (x.length() > 8)
{
isLong = true;
}
else if (x.length() < 8)
{
isLong = false;
}
return isLong;
}
//FUNCTION TO CHECK IF PASSWORD HAS DIGITS
bool checkdigits(std::string x)
{
for (int i = 0; i < x.length(); i++)
{
if (isdigit(x[i]))
{
hasDigits = true;
}
else if (not isdigit(x[i]))
{
hasDigits = false;
}
}
return hasDigits;
}
//FUNCTION TO CHECK IF PASSWORD HAS ALPHABETS
bool checkalphabets(std::string x)
{
for (int i = 0; i < x.length(); i++)
{
if (isalpha(x[i]))
{
hasAlphabets = true;
}
else if (not isalpha(x[i]))
{
hasAlphabets = false;
}
}
return hasAlphabets;
}
//MAIN FUNCTION THAT RUNS THE VALIDATION AND HANDLES LOGIC
int main()
{
std::cout << "enter new password: ";
std::string password{};
std::cin >> password;
checklen(password); //trying pass the stored cin value as argument.
checkdigits(password); //trying to pass the stored cin value as argument.
checkalphabets(password); //trying to pass the stored cin value as argument.
//the functions literally use "password" as a string instead of the stored user input.
if (isLong = true)
{
if (hasDigits = true)
{
if (hasAlphabets = true)
{
std::cout << "Your password is strong";
}
}
}
else
{
std::cout << "Your password is still weak";
}
return 0;
}
解决方案
如何将 std::cin 作为函数的参数传递?
std::cin
是一个std::istream
。因此,将它传递给函数的方式是这样的:
void function(std::istream& stream) {
// implmentation...
}
注意:我相信你不能std::istream
按值传递 s 。您必须通过引用传递它。
然后你这样称呼它:
function(std::cin);
请注意,您的程序中有其他错误在其他答案中得到了更好的解释。但这就是您通常传递std::cin
给函数的方式。
推荐阅读
- php - 如何在 PHP 8 中修复这个动态 SQL 查询功能?
- c++ - 如果在递归结束时不使用 return,为什么递归函数会产生无法识别的输出?[下面的代码]
- android - 是否可以在应用程序中显示当前的活跃用户数?
- typescript - 如何以 TypeScript 可以使用的方式获取上传文件的文件名?
- r - 通过 Docker 在 Heroku 上部署闪亮的应用程序时将警告视为错误
- linux-kernel - 我们如何通过内核映像检查内核中是否启用了无线扩展
- excel - 分析txt文件然后导出到excel
- javascript - React Native:如何根据同一对象中的其余属性有条件地设置元素样式?
- python - 如何使用 Python 生成排列线性扩展
- c# - Viewbag 值未显示在 ASP.NET MVC 视图中