简体   繁体   中英

How can I compare a string with predefined string using strcmp

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:

  • In your for loop, you use y as the counter but in the code inside the loop. you use x .
    • Given that x is 10 at that point, you always compare an inexistant user/password since your arrays contains 4 of those.
    • Also the loop limit is 5 instead of 4 so you loop one time too many. Better to use a single constant and even better let the compiler compute the size (using sizeof or std::size ).
  • If the first password tested is wrong you display an error that the password is invalid without testing the 3 other password (since you break out of the loop).

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM