1

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; 
}
1
  • 2
    Use std::string to start with. Even with the right number of equals signs, it's still wrong with character arrays. Commented Jan 6, 2013 at 21:57

2 Answers 2

7

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...

Sign up to request clarification or add additional context in comments.

5 Comments

using == operator when comparing strings is wrong, you should use str1.compare(str2), for more information read : cplusplus.com/reference/string/string/compare
@DmitryKvochkin it's not wrong. Why would you say that? This isn't Java... It's perfectly OK to compare std::strings with == in C++.
@DmitryKvochkin Have you heard about operator overloading? Probably std::string::operator== uses strcmp() under the hoods...
@DmitryKvochkin: From the same site: cplusplus.com/reference/string/operators
Thank you so much @Luchian Grigore! An to answer your side question: honestly I don’t know I guess that’s just how I typed it.
0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.