1

以下のコードを実行すると、エラーが発生します: 14 行目と 26 行目に無効な配列割り当てがあります。検索したところ、問題を解決するための答えが見つかりませんでした。

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

2 に答える 2

7

配列を割り当てることはできません。

usrname = "User"

それだけです。しないでください。

あなたが意味した

usrname == "User"

これは比較ですが、文字列は比較しません。ポインタを比較するだけです。

std::string配列またはポインターの代わりに使用して、次charと比較し==ます。

 #include <string>

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

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

補足質問 - 「username」を「usrname」に短縮するポイントは何ですか... 1文字を保存しています...

于 2013-01-06T21:56:43.347 に答える
0

strcmp などを使用する必要があります。

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

あなたがしているのは、値を比較するのではなく、値を割り当てることです。

于 2013-01-06T22:02:02.460 に答える