首页 > 解决方案 > 如何将 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;
}



标签: c++

解决方案


如何将 std::cin 作为函数的参数传递?

std::cin是一个std::istream。因此,将它传递给函数的方式是这样的:

void function(std::istream& stream) {
    // implmentation...
}

注意:我相信你不能std::istream按值传递 s 。您必须通过引用传递它。

然后你这样称呼它:

function(std::cin);

请注意,您的程序中有其他错误在其他答案中得到了更好的解释。但这就是您通常传递std::cin给函数的方式。


推荐阅读