检查"password"字符串的空格,如果找到,则返回 true:C++

Checking a "password" string for space and returning true if found: C++

本文关键字:返回 C++ true 如果 字符串 password 空格 检查      更新时间:2023-10-16

我是C++的新手,正在C++中开发一个使用向量的基本用户名和密码程序。目前,我被一个函数卡住了,该函数检查密码字符串中的空格,如果发生这种情况,就会返回true。我试图实现isspace(),但不知道它是否检查了我的字符串"密码"。提前感谢您花时间复习并以任何方式提供帮助。如果我缺少任何关键信息,我提前道歉。

    bool checkSpaces (string password) {
        for (int i = 0; i < password.length(); i++) {
            if (isspace(i)) {
                return true;
            } else {
                return false;
        }
    }

顺便说一句,我将isspace()更改为使用密码字符串,而不是循环索引。这可能是打字错误。

因为有else子句,所以循环只执行一次,要么第一个字符是空格并返回true,要么返回false。

试试纸和笔。

   bool checkSpaces (string password) {
        for (int i = 0; i < password.length(); i++) {
            if (isspace(password[i])) {
                return true;
            }
/* --> */   else {
                return false;
        }
    }

循环的内容表示,如果字符不是空格,则返回false。因此,当它碰到一个非空格字符时,无论检查了多少个字符,它都会返回。

删除else语句:

   bool checkSpaces (string password) {
        for (int i = 0; i < password.length(); i++) {
            if (isspace(password[i])) {
                return true;
            }
        }
        // If the for loop terminates, and gets here,
        // there were no spaces.
        return false;
    }