Please Help!

Im having this problem with a simple username system:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream> 
#include <cstring>  

using namespace std;

int main()
{
  char name[50];
  char username[50];
cout<<"Please set your username: ";
cin.getline(username,50);


  cout<<"Please enter your username: ";
  cin.getline(name,50);
  if(name == username){
  cout<<"correct";
  } else {
cout<<"incorrect";
}
}


and when i run and set a username and then enter the exact same it says it is incorrect, any help would be nice as I only started C++ like 3-4 days ago.
Last edited on
closed account (o3hC5Di1)
Hi there,

Try using std::string instead of char[].

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream> 
#include <cstring>  
#include <string>

using namespace std;

int main()
{
  char name[50];
  char username[50];
  std::string name, username;

  //... 


It will allow you to compare the two names as you do now, using operator ==.

Right now, using char[] what you are actually comparing is the base address of 2 char arrays, which will not be the same. You will understand this better once you learn about arrays and pointers.

Hope that helps.

All the best,
NwN
char name[50] and char username[50] are arrays. Arrays have no the comparision operator. To compare two character arrays you should use standard C function strcmp declared in header <cstring>. For example

1
2
3
4
5
6
7
8
if ( strcmp( name, username) == 0 )
{
   cout << "correct";
} 
else 
{
   cout << "incorrect";
}


Last edited on
Thank you :)
Topic archived. No new replies allowed.