How do i compare the usernames in my text file with user's input?

I want to compare u.username (user input) to the strings in my text file names.txt.

My understanding of the code I implemented:
1) I made a string u.username to take the user input
2) I created a variable string temp to store the strings coming from names.txt
3) I compared the two
4) in the instance the input matches (!=0) the program will output dou.

If its not too much to ask i'd prefer my code being fixed and then the fixes being explained. It's easier for me to understand.

this is my text file names.txt
1
2
3
4
qwerty
yesyes
pop
rin


this is my user class
1
2
3
4
5
6
7
8
class user {
	public:
		string username;
		int pass;
		string maiden;
		char choice1;
		fstream usernames;
};


this is the main code relevant for this question
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
int main() {
user u;    
string temp;
cout<<"\nAre you a new user? (y/n)";
cin>>u.choice1;
	if (u.choice1 == 'y') 
	{
		
		cout<<"please enter your username: ";
		getline (cin,u.username); //userinput
		
		//open file to read
		u.usernames.open("names.txt");

		while(u.usernames>>temp){
			if(temp.compare(u.username)!=0){
				cout<<"dou";
			}
		}
		
		u.usernames.close();
		//closing the file
		
	}
Here's how to compare two strings:

1
2
3
4
if (string_one == string_two)
{
  // they're the same!
}


1
2
3
4
if (string_one != string_two)
{
  // they're different!
}


1
2
3
4
5
6
7
while(u.usernames>>temp)
{
  if (temp != u.username)
  {
    cout<<"temp is not the same as u.username";
  }
}

Last edited on
Hello yin,

On line 13 you open the file, but how do you know it is open?

On line 16 you compare the two variables, but the if statement will only be true if the two variables are different. See http://www.cplusplus.com/reference/string/string/compare/

The class works, but I believe it is misused. For what little you are doing I do not see any need for it.

Andy
Hi Andy,

I realize using classes isn't necessary but my coursework requires us to you oop using c++ hence I added classes

yin
Hi repeater,

thanks, it worked!!

yin
use the function 'strcmp()' which is defined in <string.h>
use the condition:

if(strcmp(temp,u.username)){cout<<"dou";}

strcmp() will return 0 if both the strings are equal.

Last edited on
Hi Ultralegendary, that would work for C-style strings. For strings that are just char arrays.

However, the OP is NOT using char arrays. The OP is using C++ string objects.

strcmp is for char arrays, not C++ string objects.

You're not wrong; you're just talking about something else.
Topic archived. No new replies allowed.