2013-07-10 52 views
0

我期待帮助我的技术营员之一创建一个程序,使他们能够检查密码是否正确输入。我对这方面的知识有限,我们非常感谢您提供的任何帮助。谢谢。在C++中创建密码

//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; 
} 
+3

**那么,什么问题?** –

+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; 
} 
+0

非常感谢@Lochemage – user2569892

+2

为什么在这里没有提到'std :: string'?帮助世界。 – chris

+0

我同意克里斯。一个适当的C++答案被称为:/ –