用C ++创建密码

时间:2013-07-10 21:37:23

标签: c++ passwords char

我希望帮助我的一位科技露营者创建一个程序,让他们检查密码输入是否正确。我对此知之甚少,我们非常感谢您提供的任何帮助。谢谢。

//This lets the user input a password to enter an area

#include "stdafx.h"
#include <iostream>

using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
    cout << "Please enter the password";
     char* userData;
    do 
    {
        cin.getline(userData, 70);
            //says the data back
        cout << userData;
    }while (userData != '\n');

    if (userData == 'This is my password')
    {
        cout << "Welcome back";
    }
    else 
    {
        while(userData != 'This is my password');
        cout << "******** INTRUDER ALERT *********";
    }

    return 0;
}

1 个答案:

答案 0 :(得分:1)

我可以看到您的代码存在许多问题。首先,你可能希望你的do~while循环也包括密码检查条件,否则你只是在用户输入一个空白行后才检查密码(如果你的密码实际上是一个空白行,那只会匹配密码) 。 cin.getline()提示用户输入一个字符串,因此只有在用户键入字符串后才会执行下一行。

使用'=='运算符无法完成C ++中的字符串比较,这不具备您想要的效果。在你的情况下,'=='运算符将字符串执行ascii字符代码检查字符串的第一个字母,只有那。如果要进行字符串比较,则需要使用比较函数,如strcmp(),如果没有差异则返回0。

你也没有分配任何内存用于你的字符串变量,这在C ++中是一个很大的禁忌。许多脚本语言都不需要这样,但是C ++中的字符串必须提前分配到你想要的大小才能使用它们。

#include "stdafx.h"
#include <iostream>

using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
    cout << "Please enter the password";
    char userData[71];   // I've allocated 71 characters to this string, which matches the amount of characters you accept in your getline call (plus one more for the required end of string character '\0').
    do 
    {
        cin.getline(userData, 70);
            //says the data back
        cout << userData;

        // Notice, I've moved this block inside the loop, as it needs to be tested after each password entry rather than after the user has input an empty line.
        if (!strcmp(userData, "This is my password")) // I've changed this statement to use the strcmp function to actually compare the values of the entire strings together.  The result of this function is the total number of differences found, so if it returns 0 that means the strings are the same.  Also note, I am using double quotes instead of single for the password value.
        {
            cout << "Welcome back";
            break; // I've added a break here to break out of the loop when the user inputs the correct password.
        }
        else 
        {
            // Removed the infinite loop, as it has no purpose other than locking up the program.
            cout << "******** INTRUDER ALERT *********";
        }

    }while (strlen(userData) != 0); // I'm not too sure about this, but I think if you enter a blank line it does not contain the '\n' within itself.  Instead, I've opted to use the strlen() function which tells you how many letters are in the given string.

    return 0;
}