How can I compare a string with predefined string using strcmp
?
#include <conio.h>
#include <iostream.h>
#include <stdio.h>
#include <string.h>
char user[12];
char pass[12];
char usr[4][12] = {"nathan", "marco", "denz", "ana"};
char pss[4][12] = {"admin", "two", "sad", "three"};
int x, y;
main() {
clrscr();
for (x = 0; x < 10; x++) {
cout << "-";
}
cout << "Username: ";
scanf("%s", &user);
cout << "Password: ";
scanf("%s", &pass);
for (y = 0; y < 5; y++) {
if ((strcmp(user, usr[x]) == 0) && (strcmp(pass, pss[x]) == 0)) {
cout << "Log-in Successful";
break;
} // if
else {
cout << "Log-in Failed! Try Again!";
break;
} // else
} // for
getch();
} // main
The strcmp()
method takes two arguments, in your case the first would be the password
or username
(key) that will be compared against the second word given being user input
(value). So for example
strcmp(key, value);
This returns an integer value, 0 if the strings match and either a negative or positive depending on the ASCII value of the characters if they don't match.
Your code has many problems:
for
loop, you use y
as the counter but in the code inside the loop. you use x
.
x
is 10 at that point, you always compare an inexistant user/password since your arrays contains 4 of those.sizeof
or std::size
).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.