zachpescitelli
zachpescitelli

Reputation: 13

Invalid array assignment?

When I run the code below I get the error : invalid array assignment on lines 14 and 26. I am fairly new (1 week) to c++ so I am a bit confused. I searched and could not find an answer to solve my problem.

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

Upvotes: 1

Views: 9318

Answers (2)

mgr
mgr

Reputation: 342

you need to use strcmp or similar.

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

what you are doing is assigning a value not comparing values.

Upvotes: 0

Luchian Grigore
Luchian Grigore

Reputation: 258548

You can't assign arrays, and

usrname = "User"

does just that. Don't.

You meant

usrname == "User"

which is a comparison, but won't compare your strings. It just compares pointers.

Use std::string instead of char arrays or pointers and compare with ==:

 #include <string>

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

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

Side question - what's the point of shortening "username" to "usrname"... you're saving a single character...

Upvotes: 7

Related Questions