Whenever I run the program and type in jane1234 as the username, it keep saying "Invalid Username. Please try again.". Anything wrong with the code? Any help is appreciated. Thanks.
Can the code be made so that if the user type in the wrong username, it will say the username is incorrect instead of asking for password. If the username is typed correctly, it will prompt the user to enter their password.
FFS... Good work ignoring people who hinted to an actual solution, plus confusing answers.
The guy doesn't use C++, std::string::operator== is useless.
Also you do not compare strings with == or with !=, but you use STRCMP.
C++'s std::string allows you to use ==.
Otherwise you're just comparing data location, not their content (eg, is data stored in variable "name" at the same memory position of constant "yourusername"? probably not, but what matters is the content of the locations, not the location itself)
Sorry if I ignored you, I didn't mean to ignore you. Is it possible to just include stdio.h only without string.h to come out with the code? Just a question. Thanks.
The only other way is to build a clone of strcmp.
Another alternative is memcmp if you know the length of the string... But still requires string.h.
Why do you not want to use string.h?
#include <stdio.h>
int equals( constchar* a, constchar* b )
{
if( a == NULL || b == NULL ) return a == NULL && b == NULL ; // equal if both are NULL
// invariant a and b are both non-NULL
for( ; *a && *b ; ++a, ++b ) if( *a != *b ) return 0 ; // not equal if there is a mismatch
// invariant: all characters up to the end of either one of the two strings are equal
return *a == 0 && *b == 0 ; // equal if we have reached the end of both strings
}
int main()
{
constchar expected_username[] = "jane1234" ;
enum { MAX_USERNAME_SZ = 99 } ; // avoid magic numbers
char username[ MAX_USERNAME_SZ + 1 ] = "" ; // +1 for the terminating null character
char format[32] = "" ; // avoid magic numbers in the format string too
sprintf( format, "%%%us", MAX_USERNAME_SZ ) ; // writing maintainable code in C is hard
// especially when i/o is involved
int fields_read = scanf( format, username ) ; // **** not &user_name ****
if( fields_read == 1 )
{
printf( "%s: ", username ) ;
if( equals( username, expected_username ) ) puts( "correct" ) ;
else puts( "incorrect" ) ;
}
}
this way I'd created atm login system, you can get more ideas via it :) Here basically you can create as many usernames & passwords & change them right from where they were declared in the start of the source code :)
Except that it doesn't look like C at all, especially the first two lines.
You can safely follow JLBorges' code.
I'd just change line 5's "then" statement to return a==b;
And line 11 to return *a == *b;