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; 
}
wallyk
58.1k17 gold badges92 silver badges155 bronze badges
asked Jan 6, 2013 at 21:55
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...

answered Jan 6, 2013 at 21:56
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.

answered Jan 6, 2013 at 22:02

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.