C+中的用户名/密码检查器出错+; 我目前正在尝试学习一些C++程序,并决定让自己成为一个基本的3次尝试用户名和密码检查器来练习我读过的一些内容。问题是,当我运行程序并首先输入错误的用户名和密码时,如果在第二次或第三次尝试中输入,程序将不再识别正确的用户名和密码。我已经看了很长一段时间了,似乎无法让它发挥作用。 我甚至还包括了一个当前已注释掉的行,以确保程序正在读取正确的输入 #include <iostream> #include <string> using namespace std; int main() { int attempts=0; string username, password; while (attempts < 3) { cout<<"\nPlease enter your username and password seperated by a space.\n"; getline( cin, username, ' '); cin>>password; if (username == "Ryan" && password == "pass") { cout<<"\nYou have been granted access."; return 0; cin.get(); } else { attempts++; //cout<<username <<" " <<password << "\n"; cout<<"Incorrect username or password, try again."; cout<<"\nAttempts remaining: "<<3-attempts <<"\n"; } } cout<<"\nOut of attempts, access denied."; cin.get(); } #包括 #包括 使用名称空间std; int main() { int=0; 字符串用户名、密码; 而(尝试次数在空格和换行符处分割输入。它基本上跳过任何初始空格,然后读入,直到它遇到另一个空格并停止。 cin >> username; cin >> password;

C+中的用户名/密码检查器出错+; 我目前正在尝试学习一些C++程序,并决定让自己成为一个基本的3次尝试用户名和密码检查器来练习我读过的一些内容。问题是,当我运行程序并首先输入错误的用户名和密码时,如果在第二次或第三次尝试中输入,程序将不再识别正确的用户名和密码。我已经看了很长一段时间了,似乎无法让它发挥作用。 我甚至还包括了一个当前已注释掉的行,以确保程序正在读取正确的输入 #include <iostream> #include <string> using namespace std; int main() { int attempts=0; string username, password; while (attempts < 3) { cout<<"\nPlease enter your username and password seperated by a space.\n"; getline( cin, username, ' '); cin>>password; if (username == "Ryan" && password == "pass") { cout<<"\nYou have been granted access."; return 0; cin.get(); } else { attempts++; //cout<<username <<" " <<password << "\n"; cout<<"Incorrect username or password, try again."; cout<<"\nAttempts remaining: "<<3-attempts <<"\n"; } } cout<<"\nOut of attempts, access denied."; cin.get(); } #包括 #包括 使用名称空间std; int main() { int=0; 字符串用户名、密码; 而(尝试次数在空格和换行符处分割输入。它基本上跳过任何初始空格,然后读入,直到它遇到另一个空格并停止。 cin >> username; cin >> password;,c++,password-checker,C++,Password Checker,由于getline,您的用户名在第一次尝试后包含一个换行符'\n' 从更改您的cin用法 getline( cin, username, ' '); cin>>password; 到 修复您的问题顺便说一句,中的返回0;cin.get();如果块没有意义。A返回是整个函数的结尾,cin.get()不会被执行。是的,我想这是早期阶段留下的。不过谢谢你指出。我肯定可以养成回去清理自己的习惯。如果你不介意我问的话,是什么让程序知道在空间分割输入?老实说,我不认为这是错误的ould希望检

由于getline,您的用户名在第一次尝试后包含一个换行符'\n'

从更改您的cin用法

getline( cin, username, ' ');
cin>>password;


修复您的问题

顺便说一句,
中的
返回0;cin.get();
如果
块没有意义。A
返回
是整个函数的结尾,
cin.get()
不会被执行。是的,我想这是早期阶段留下的。不过谢谢你指出。我肯定可以养成回去清理自己的习惯。如果你不介意我问的话,是什么让程序知道在空间分割输入?老实说,我不认为这是错误的ould希望检查它,但相反,它会接受整个输入并将其作为“username”的值抛出。这是cin流的标准行为:它读取一个字符串,直到第一个分隔符标记,这是一个blank@Ryan提取操作符
>
在空格和换行符处分割输入。它基本上跳过任何初始空格,然后读入,直到它遇到另一个空格并停止。
cin >> username;
cin >> password;