无效的数组赋值?

时间:2013-01-06 21:55:54

标签: c++

当我运行下面的代码时,我得到错误:第14行和第26行的数组分配无效。我相当新(1周)到c ++所以我有点困惑。我搜索过,找不到解决问题的答案。

#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; 
}

2 个答案:

答案 0 :(得分:7)

您无法分配数组,

usrname = "User"

就是这么做的。不。

你的意思是

usrname == "User"

这是一个比较,但不会比较您的字符串。它只是比较指针。

使用std::string代替char数组或指针,并与==进行比较:

 #include <string>

 //...
 std::string usrname;
 cin << usrname;

  if (usrname == "User")
  //          ^^
  //   note == instead of =

附带问题 - 将“用户名”缩短为“usrname”有什么意义......你要保存一个角色......

答案 1 :(得分:0)

你需要使用strcmp或类似的东西。

if (!strcmp(usrname, "User"))
{
   cout << "Username correct!";
}

您正在做的是分配一个不比较值的值。

相关问题