Program for Password in C++ - c++

Password program not working....pls help....for right input also it says wrong password
#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<iostream.h>
void main()
{
clrscr();
int ctr=0;
int o;
char pass[5];
cout<<"enter password";
for(int i=0;i<5 && (o=getch())!=13 ;i++)
{
pass[i]=o;
putch('*');
}
ctr=strcmp(pass,"luck");
cout<<ctr;
if(ctr==0)
{
cout<<"welcome";
}
else
{
cout<<"wrong password";
}
getch();
}
I want to know why this password program not working....is their any other way

To be able to use strcmp(), you need to NUL-terminate pass. You also need to make sure that pass is large enough to accommodate the NUL.

As <conio.h> is in use, I'm assuming Windows is being used. For those who are interested, here is a start on the proper way to do this. I input a line as the password, ending when enter is pressed, and don't show asterisks, as they give away the length pretty easily.
//stop echoing input completely
HANDLE inHandle = GetStdHandle(STD_INPUT_HANDLE); //get handle to input buffer
DWORD mode; //holds the console mode
GetConsoleMode(inHandle, &mode); //get the current console mode
SetConsoleMode(inHandle, mode & ~ENABLE_ECHO_INPUT); //disable echoing input
//read the password
std::string password; //holds our password
std::getline(std::cin, password); //reads a line from standard input to password
//compare it with the correct password
std::cout << (password == "luck" ? "Correct!\n" : "Wrong!\n"); //output result
//return console to original state
SetConsoleMode(inHandle, mode); //set the mode back to what it was when we got it
Of course there are things you can do to improve it (a hardcoded password string is never a good thing), and go ahead and do so if you wish, but the point is that it works as a basic password input system and has an easy-to-follow structure. You can still use the things you love when getting a password input, rather than going one character at a time and resorting to C strings and code.

Related

Why does scanf_s() isn't working second time I am calling it in order to verify if user provided correct input?

I am writing an application with a menu and I am asking the user to provide an integer representing an option
from the menu
1. Option 1
2. Option 2
3. Option 3
...
This option is stored in a variable called
option
I want to avoid wrong input such as "12a", "1a2", "anyString" and I've read that this can be achieved by storing return value of scanf_s() function.
So I stored it in a variable called
ret
and now I want that every time user provides wrong input to prompt them to enter a new value.
So I wrote something like this:
int ret = scanf_s("%d", &option);
while (!ret)
{
cout << "Provide an integer, not a string! :)\n";
ret = scanf_s("%d", &option);
}
The problem is when it enters the while it is not allowing user to enter a new value and hence the value of ret never changes, making it run endlessly.
How can I achieve what I am looking for?
When scanf_s fails to convert an integer, the offending input stays in the input stream. Calling scanf_s("%d", &option) again will produce the same result until some characters are removed from the input stream. Note also that using scanf_s or scanf directly from stdin is error prone: the newline entered by the user stays in the input stream and will be read by a subsequent call to getchar() or fgets(), potentially causing unexpected behavior.
To avoid these pitfalls, it is recommended to read one line at a time with fgets() and convert it with sscanf() this way:
#ifdef _MSC_VER
#define _CRT_SECURE_NO_WARNINGS
#endif
#include <stdio.h>
int main() {
char buf[80];
int option;
char cc;
for (;;) {
print_menu(); // output the menu options
if (!fgets(buf, sizeof buf, stdin)) {
/* end of file reached: break from the loop */
break;
}
/* parse exactly one integer with optional leading and trailing whitespace */
if (sscanf(buf, "%d %c", &option, &cc) != 1) {
printf("invalid input: %s", buf);
printf("enter one integer exactly\n");
continue;
}
printf("option is %d\n", option);
// handle option
}
return 0;
}

Using KeyPress in C++ from string input creates errors

Solved: Check the void SendInputString( std::wstring &str) function in this answer
I am developing an executable in C++ which can be given a string as a command-line parameter and it will be typed emulating the keyboard; using keypresses.
In the format on command line:
{program name} {string to reproduce} {time between individual keypresses in ms}
This is my code:
#define WINVER 0x0500
#include <windows.h>
void chartype(char x , INPUT &input, unsigned int pause_time){
input.ki.wVk=VkKeyScanA(x);
//Verifies character and allots the key to the keyboard
//cout<<x; //Old check code
Sleep(pause_time);
SendInput(1,&input,sizeof(INPUT));
//To send input
return;
}
int main(int argc , char** argv){
//Initializing a GUI Keyboard Set
INPUT input;
input.type=INPUT_KEYBOARD;
//Assigning Input Variables
string str = argv[1];
size_t n = str.size();
unsigned int pause_time = stoi(argv[2]);
//Sending individual string characters
for(size_t i =0 ; i<n ; ++i){
chartype(str[i] , input , pause_time);
}
//Shutting Keyboard
input.ki.dwFlags=KEYEVENTF_KEYUP;
SendInput(1, &input,sizeof(INPUT));
return 0;
}
However, the string is not exactly executed. For example if I input the string PASS_INPUT, it renders pass-input. Also, the output is sensitive to whether or not Caps Lock is on or not.
I assume it is happening because it only kind of emulates pressing the specific key on the keyboard, and thus assumes a default value, however I want it to present exact outputs, such as %9Xa{ to give %9Xa{ and not 59xa[ which is happening presently.
I am sorry if I could not frame the question well enough. I am new to this keyboard emulation, and am not able to exactly understand what to do.
I would like to know what modification should be made to render the string as expected.
Can use the function SendInputString( std::wstring &str) from this answer

CMD Prompt C++: Limiting literals entered on screen

I hope the question isn't to ambiguous.
when I ask:
int main()
{
string name = {""};
cout << "Please enter a name: " << endl;
getline(cin, name);
//user enters 12 characters stop displaying next literal keypresses.
enter code here
}
I would like to be able to limit the amount of times the user can enter a char on screen. Example, the screen stops displaying characters after length 12?
If so what would be the library and command line for doing something like this?
Wanting to this as, I have a ascii art drawn on the CMD, and when I cout the statement at x,y anything over 12 characters long inputed draws over the ascii art.
I hope this makes sense :'{ Thank you!
By default the console is in cooked mode (canonical mode, line mode, ...). This means
that the console driver is buffering data before it hands it to your application
characters will be automatically echoed back to the console by the console driver
Normally, this means that your program only ever gets hold of the input after a line ends, i.e. when enter is pressed. Because of the auto-echo, those character are then already on screen.
Both settings can be changed independently, however the mechanism is --unfortunately-- an OS-specific call:
For Window it's SetConsoleMode():
HANDLE h_stdin = GetStdHandle(STD_INPUT_HANDLE);
DWORD mode = 0;
// get chars immediately
GetConsoleMode(hStdin, &mode);
SetConsoleMode(hStdin, mode & ~ENABLE_LINE_INPUT));
// display input echo, set after 12th char.
GetConsoleMode(hStdin, &mode);
SetConsoleMode(hStdin, mode & ~ENABLE_ECHO_INPUT));
As noted by yourself, Windows still provides conio.h including a non-echoing _getch() (with underscore, nowadays). You can always use that and manually echo the characters. _getch() simply wraps the console line mode on/off, echo on/off switch into a function.
Edit: There is meant to be an example on the use of _getch(), here. I'm a little to busy to get it done properly, I refrained from posting potentially buggy code.
Under *nix you will most likely want to use curses/termcap/terminfo. If you want a leaner approach, the low level routines are documented in termios/tty_ioctl:
#include <sys/types.h>
#include <termios.h>
struct termios tcattr;
// enable non-canonical mode, get raw chars as they are generated
tcgetattr(STDIN_FILENO, &tcattr);
tcattr.c_lflag &= ~ICANON;
tcsetattr(STDIN_FILENO, TCSAFLUSH, &tcattr);
// disable echo
tcgetattr(STDIN_FILENO, &tcattr);
tcattr.c_lflag &= ~ECHO;
tcsetattr(STDIN_FILENO, TCSAFLUSH, &tcattr);
You can use scanf("%c",&character) on a loop from 1 to 12 and append them to a pre-allocated buffer.
As in my comments, I mentioned a method I figured out using _getch(); and
displaying each char manually.
simplified version:
#include <iostream>
#include <string>
#include <conio.h>
using namespace std;
string name = "";
int main()
{
char temp;
cout << "Enter a string: ";
for (int i = 0; i < 12; i++) { //Replace 12 with character limit you want
temp = _getch();
name += temp;
cout << temp;
}
system("PAUSE");
}
This lets you cout each key-press as its pressed,
while concatenating each character pressed to a string called name.
Then later on in what ever program you use this in, you can display the full name as a single string type.

when i enter password the first alphabet comes different not what i have entered

this is the code for accepting a string and display '*' at each place of alphabet(for password).For example i have entered password than it shows #assword instead of password when i cout the string.please help me.....
#include<iostream.h>
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
char pass[5];
cout<<"\n\n Pass : ";
int i=0;
pass[0]=getch();
while(pass[i]!=13)
{ i++;
cout<<"*";
pass[i]=getch();
}
cout<<"\n\n";
cout<<pass;
getch();
}
You've only allocated 5 bytes for the password, but read an arbitary number of bytes, which will lead to illegal accesses and basically all sorts of (potentially) random stuff happening, including odd corruptions like you have seen.
Also, you fail to null terminate your char array, so you might get random stuff printed after the password - a pass[++i]='\0'; placed after the loop will fix that.
Try increasing it to a much larger value and see if that fixes the issue.
If not, can you paste the entire output - do the * get messed up? is it just the

How to let users put in only one character?

so I have a text-based Adventure Game and its running smoothly but one of my "beta testers" noticed that he could select multiple numbers in the first cin spot and it would use those values for the rest of the game. Can I manually put a block on how many characters the user has to type?
Here's my program
#include <iostream>
#include <stdio.h>
#include <cstdio>
#include <cstdlib>
char Choice;
char my_name;
using namespace std;
int main()
{
printf("You come out of darkness.\n");
printf("Confused and tired, you walk to an abandoned house.\n");
printf("You walk to the door.\n");
printf("What do you do?\n");
printf("1. Walk Away.\n");
printf("2. Jump.\n");
printf("3. Open Door.\n");
printf(" \n");
cin >> Choice;
printf(" \n");
if(Choice == '1')
{
printf("The House seems too important to ignore.\n");
printf("What do you do?\n");
printf("1. Jump.\n");
printf("2. Open Door.\n");
printf(" \n");
cin >> Choice;
printf(" \n");
And so on, you get the gist of it
This is largely platform dependent and there is no easy catch-all solution, but a working solution is to use std::getline to read one line at a time and either ignore everything but the first character or complain if more than one was entered.
string line; // Create a string to hold user input
getline(cin,line); // Read a single line from standard input
while(line.size() != 1)
{
cout<<"Please enter one single character!"<<endl;
getline(cin, line); // let the user try again.
}
Choice = line[0]; // get the first and only character of the input.
Thus will prompt the user to enter a single character if they enter more or less (less being an empty string).
If you want the player to be able to press keys like 1, 2 or 3 without having to press enter, you're quickly getting into platform-specific code. On Windows, the old-school (and by old-school, I mean "dating back to the DOS days of the 80s") console way is with the conio routines.
There's nothing within standard C++ which defines that sort of interface, though.
Another approach is to use getline to get an entire line's worth of text every time, and then discard everything past the first character. That would keep you within plain C++, and fix your immediate issue.