当我运行下面的代码时,我收到错误:第 14 行和第 26 行的数组分配无效。我是 c++ 的新手(1 周),所以我有点困惑。我进行了搜索,但找不到解决我问题的答案。
#include <iostream>
int main()
{
using namespace std;
char usrname[5];
char psswrd[9];
cout << "Please enter your username:";
cin >> usrname;
if (usrname = "User")
{
cout << "Username correct!";
}
else
{
cout << "Username incorrect!";
}
cout << "Please enter your password:";
cin >> psswrd;
if (psswrd = "password")
{
cout << "The password is correct! Access granted.";
}
else
{
cout << "The password is incorrect! Access denied.";
}
return 0;
}
最佳答案
你不能给数组赋值,而且
usrname = "User"
就是这样做的。不要。
你的意思是
usrname == "User"
这是一个比较,但不会比较您的字符串。它只是比较指针。
使用std::string
代替char
数组或指针并与==
比较:
#include <string>
//...
std::string usrname;
cin << usrname;
if (usrname == "User")
// ^^
// note == instead of =
附带问题 - 将“用户名”缩短为“用户名”有什么意义...您正在保存单个字符...
关于c++ - 数组赋值无效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14187217/