我似乎无法弄清楚为什么get_password函数调用将始终返回qwert,无论我传入函数的字符串是什么。我的问题是我无法看到这个函数中的字符串比较出了什么问题。
string get(string askfor, int numchars, string input)
{
cout << askfor << "(" << numchars << " characters): ";
cin >> input;
return input;
}
string get_password(string name)
{
string pwd;
if (name == "botting"){
pwd = "123456";
}
else if (name == "ernesto") {
pwd = "765432";
}
else if (name == "tong") {
pwd = "234567";
}
else {
pwd = "qwert";
}
return pwd;
}
int main()
{
string name;
string pwd;
string passwd;
cout << "Address of name =" << &name << "\n";
cout << "Address of pwd =" << &pwd << "\n";
cout << "Address of passwd =" << &passwd << "\n";
bool authenticated = false;
while (!authenticated)
{
// call one
string name1 = get("Name", 7, name);
cout << "call one returned: " << name1 << endl;
// call two
string pass1 = get_password(name);
cout << "call two returned: " << pass1 << endl;
//call three
string pass2 = get("Password", 7, passwd);
cout << "call three returned: " << pass2 << endl;
// compare the two passwords
authenticated = false;
if (pass1 == pass2) {
cout << "Welcome " << name << "\n";
authenticated = true;
}
else {
cout << "Please try again\n";
}
}
return 0;
}
答案 0 :(得分:1)
将name1
传递给第二个电话:
// call one
string name1 = get("Name", 7, name);
cout << "call one returned: " << name1 << endl;
// call two
string pass1 = get_password(name1); // change this variable
cout << "call two returned: " << pass1 << endl;
get()
将名称返回到name1
字符串,并且不会更新name
变量本身,因为此name
仍为空字符串。
答案 1 :(得分:0)
那是因为你永远不会分配name
任何内容。它被初始化为""
,并且永远不会改变。由于这与get_password
中的所有案例都不匹配,因此它始终属于else
案例,这会产生"qwert"
。
我认为问题在于您的get
函数会更好地编写如下:
string get(string askfor, int numchars)
{
string input; // input shouldn't be an argument
cout << askfor<<"("<<numchars<<" characters): ";
cin >> input;
return input;
}
您可以使用结果分配到name
:
name = get("Name", 7);
答案 2 :(得分:0)
您只需要通过参考而不是值。
string get(string askfor, int numchars, string &input)
{
cout << askfor << "(" << numchars << " characters): ";
cin >> input;
return input;
}