c++ - 数组赋值无效?

标签 c++

当我运行下面的代码时,我收到错误:第 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/

相关文章:

c++ - std::wcout 将不会在一定数量的字符后打印

c++ - 模板打印函数 C++

c++ - 使用抽象基类型在 C++ 中进行类型推断

c++ - 删除指向不完整类型和智能指针的指针

c++段错误(核心转储)与模数

c++ - 从 QTWidget 隐藏页面/选项卡 - QT 5.5

c++ - 将 GetLastError() 变成异常

c++ - 使用 BOOST_FUSION_ADAPT_STRUCT 调整结构时出现编译器错误

c++ - GNU C 内联汇编中的输入操作数 `"m"(var )` and Output Operand ` "=m"(var)` ?不使用任何指令作为屏障?

c++ - OpenCV:来自 decomposeHomographyMat 的奇怪旋转和平移矩阵