Creating a Password in C++ -
i looking 1 of tech campers create program allows them check if password entered correctly. have limited knowledge , appreciate provide. thank you.
//this lets user input password enter area #include "stdafx.h" #include <iostream> using namespace std; int _tmain(int argc, _tchar* argv[]) { cout << "please enter password"; char* userdata; { cin.getline(userdata, 70); //says data cout << userdata; }while (userdata != '\n'); if (userdata == 'this password') { cout << "welcome back"; } else { while(userdata != 'this password'); cout << "******** intruder alert *********"; } return 0; }
i can see number of issues code. first, want do~while loop include password check condition well, otherwise checking password after user types in blank line (which match password if password literally blank line). cin.getline() prompts user string, next line executed after user types in string.
string comparisons in c++ cannot done using '==' operator, not have effect intend. '==' operator in case literally perform ascii character code check on first letter of strings , that. if want string comparison, need use compare function such strcmp() returns 0 if there no differences.
you not allocating memory use string variable, big no-no in c++. many scripting languages don't require this, strings in c++ must allocated ahead of time size desire before can used.
#include "stdafx.h" #include <iostream> using namespace std; int _tmain(int argc, _tchar* argv[]) { cout << "please enter password"; char userdata[71]; // i've allocated 71 characters string, matches amount of characters accept in getline call (plus 1 more required end of string character '\0'). { cin.getline(userdata, 70); //says data cout << userdata; // notice, i've moved block inside loop, needs tested after each password entry rather after user has input empty line. if (!strcmp(userdata, "this password")) // i've changed statement use strcmp function compare values of entire strings together. result of function total number of differences found, if returns 0 means strings same. note, using double quotes instead of single password value. { cout << "welcome back"; break; // i've added break here break out of loop when user inputs correct password. } else { // removed infinite loop, has no purpose other locking program. cout << "******** intruder alert *********"; } }while (strlen(userdata) != 0); // i'm not sure this, think if enter blank line not contain '\n' within itself. instead, i've opted use strlen() function tells how many letters in given string. return 0; }
Comments
Post a Comment