无论我在if语句中键入什么,代码都无法像我的教授所希望的那样工作。
我的助教说这是语法错误,但没有为我提供更多背景信息。
“您使用的语法不正确。如果您要对首字母进行比较以abc为例,您会说if(initials ==“ abc”)。同样,对每个条件都执行相同的操作。“
我真的不明白他的意思。
如果我更改if语句以添加引号,它将始终拒绝访问。如果我将其保留原样,它将始终授予访问权限。
这是我的代码:
#include <iostream>
#include <string>
using namespace std;
int main(){
cout<<"Gain entry with your user information and password." <<endl;
cout<<"For security purposes, the information will not be echoed to the screen." <<endl;
cout<<"Please enter your initials: " <<endl;
string initials;
cin>>initials;
cout<<"Please enter your age: " <<endl;
int age;
cin>>age;
cout<<"Please enter your password: " <<endl;
string password;
if ( password == initials,age) {
cout<<"Access granted!" <<endl;
}
else {
cout<<"Access denied!" <<endl;
}
return 0;
}
这里是说的:
==================== YOUR OUTPUT =====================
0001: Gain~entry~with~your~user~information~and~password.
0002: For~security~purposes,~the~information~will~not~be~echoed~to~the~screen.
0003: Please~enter~your~initials:
0004: Please~enter~your~age:
0005: Please~enter~your~password:
0006: Access~granted!
=================== MISMATCH FOUND ON LINE 0006: ===================
ACTUAL : Access~granted!
EXPECTED: Access~denied!
======================================================
Adjust your program and re-run to test.
Test 2 failed
ccc_0bc38e1b3b_10207@runweb5:~$ ^C
ccc_0bc38e1b3b_10207@runweb5:~$
您的密码永远不会被初始化,因此它是默认构造的,实际上是一个空字符串。 (您正在将首字母与空字符串进行比较)修改这些行:
cout<<"Please enter your password: " <<endl;
string password;
像这样以便初始化password变量。
cout<<"Please enter your password: " <<endl;
string password;
cin >> password;
编辑:您还提到过您想将密码与首字母+年龄进行比较
// to_string will convert the integer (age) to a string so we can concatenate it with initials
string correct_pass = initials + std::to_string(age);
if ( password == correct_pass) {
cout<<"Access granted!" <<endl;
}else {
cout<<"Access denied!" <<endl;
}
我不认为这条线正在做您认为正在做的事情:
if ( password == initials,age) {
...特别是,age
部分没有任何用处;仅将年龄值丢弃,并且不将其用作字符串比较的一部分。
也许您想要的更像
if ((password == initials)&&(age >= 18)) {
?