我可以看到您的代码存在许多问题。首先,您可能希望您的 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;
}