Advertisement
alaestor

example string cmp

Jul 18th, 2017
199
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.19 KB | None | 0 0
  1. /*
  2.  * FGL - roleplay.FutureGadgetLab.net posted by @alaestor
  3.  * the following is a simple guess the password example
  4.  * without using strcmp or other dedicated string functions.
  5.  * The for() can be compacted to be on one line. Newlined for
  6.  * the 79 char limit. Makes use of in-condition assignment.
  7.  */
  8.  
  9. #include <cstdio>
  10.  
  11. bool AreStringsTheSame(const char *strA, const char *strB)
  12. { // only works with null terminated strings!
  13.     bool cmp;
  14.     for (
  15.         int i = 0;
  16.         (cmp = strA[i] == strB[i]) && (strA[i] != '\0' && strB[i] != '\0');
  17.         i++
  18.     );
  19.     return cmp;
  20. }
  21.  
  22. int main()
  23. {
  24.     char buffer[80];
  25.     const char *secret = "password";
  26.     // if your password is password, you're a horrible person
  27.  
  28.     printf("\n\nEnter the password: ");
  29.     if ( scanf("%79s", buffer) == EOF )
  30.         return 0; // error:  something went horribly wrong
  31.  
  32.     printf("\n\nYour answer of %s was ", buffer);
  33.     if (AreStringsTheSame(buffer, secret))
  34.     { // optimal for ternary but if{}else{} for clarity.
  35.         puts("correct :D");
  36.     }
  37.     else
  38.     {
  39.         puts("incorrect :(");
  40.     }
  41.  
  42.     char c; // clear stupid input buffer and wait for user
  43.     while ((c = getchar()) != '\n' && c != EOF);
  44.     puts("\n\nPress Enter to exit");
  45.     getchar();
  46.  
  47.     return 0;
  48. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement