So I was to create a program that would verify a password is created correctly. To pass verification, the user must enter 6 or more characters, have at least one lower case letter, one upper case letter, and one digit. The catch is I had to use only the cstring (and of course cctype) library and not the string library. The program runs fine if the user creates an incorrect password, if they successfully create a good password then it sometimes (not sure why sometimes) it crashes. An answer to this, will help me solidify my understanding more on pointers an allocation of memory in terms of it being dynamic. With that here is the program in question.
#include <iostream>
#include <cctype>
#include <cstring>
bool isVerifyAccepted(char*, int);
using namespace std;
int main() {
const int SIZE = 6;
char *userPass = new char[SIZE];
cout << "Verify you have a good password\na good password has to be at least six characters long\n"
<< "have at least on uppercase and one lowercase letter and at least one digit" <<endl <<endl;
cout << "enter a password below" <<endl <<endl;
cin >> userPass;
int userSizePass = strlen(userPass);
char testPassWord[userSizePass];
int count = 0;
while (count < userPass[count]) {
testPassWord[count] = userPass[count];
count++;
}
isVerifyAccepted(testPassWord, userSizePass);
delete[] userPass;
userPass = NULL;
//system("pause");
return 0;
}
bool isVerifyAccepted(char *pass, int size){
bool verify[3];
if(size <= 6){
cout << "Password is too short "<<endl;
return false;
}
for(int i = 0; i<size; i++){
if(islower(pass[i])){
verify[0] = true;
break;
}else{
verify[0] = false;
}
}
for(int i = 0; i<size; i++){
if(isupper(pass[i])){
verify[1] = true;
break;
}else{
verify[1] = false;
}
}
for(int i = 0; i<size; i++){
if(isdigit(pass[i])){
verify[2] = true;
break;
}else{
verify[2] = false;
}
}
if(verify[0] == false){
cout << "You need at least one lowercase letter" << endl;
}
if(verify[1] == false){
cout << "You need at least one uppercase letter" << endl;
}
if(verify[2] == false){
cout << "You need at least one digit" << endl;
}
if((verify[0] == true) && (verify[1] == true) && (verify[2] == true)){
cout << "You have a good password, you met the criteria " <<endl;
}
return verify;
}
Because of this line according to the debugger : const int SIZE = 6.
Increase the size to 32 or some number larger than 6.
Some passwords are longer than 6 characters.
Related
As you can see from the title I want to check password but with do while loop. What I want to do is, asking the user to enter the password and if the password is incorrectly entered 3 times, the program should exit.
Here is the code, I hope you understand what I want to do
#include <iostream>
#include <conio.h>
using namespace std;
int main()
{
int n = 0;
char s[10] = {'s','a','m','e','d'};
char unos[10];
int i;
do
{
for (i = 0; i < 5;i++) {
unos[i] = _getch();
_putch('*');
}
cout << endl;
for (i = 0; i < 5; i++)
{
if (unos[i] == s[i])
{
cout << "Your password is correct" << endl;
break;
}
else if (unos[i] != s[i])
{
do
{
cout << "Your password is incorrect" << endl;
cout << "Enter again: ";
for (i = 0; i < 5;i++) {
unos[i] = _getch();
_putch('*');
}
n++; // how many times user entered the password
}while(unos[i] != s[i]);
}
}
}while(unos[i] != s[i] && n < 3);
return 0;
}
The console output is correct, or it does what I want if I enter the correct password for the first time but if I made a mistake it doesnt do anything after that or actually it does ask me again to enter the password but it doesnt, show the message Your password is correct.
If you now how to do this task even with recursion it would help me a lot.
Thanks in advance :)
Following loop will never end:
do
{
cout << "Your password is incorrect" << endl;
cout << "Enter again: ";
for (i = 0; i < 5;i++) {
unos[i] = _getch();
_putch('*');
}
n++; // how many times user entered the password
}while(unos[i] != s[i]);
1) n < 3 is done out of this loop, so number of times is not considered
2) at the moment of }while(unos[i] != s[i]); i = 5 (you declared i earlier), so you are comparing unos[5] and s[5]. These values are not initialized.
There are other issues in this code:
If the mentioned loop would end it would exit to for (i = 0; i < 5; i++), it also has no check of n.
The main issue in my opinion is that you are checking only the first letter of entered password, so entering "sqwer" would give you "Your password is correct".
This code should be completely reworked.
Working example (if continuing your idea) would look like this:
#include <conio.h>
#include <iostream>
using namespace std;
int main() {
int n = 0;
char s[10] = { 's', 'a', 'm', 'e', 'd' };
char unos[10];
bool is_pwd_correct = false;
do {
for (int i = 0; i < 5; i++) {
unos[i] = _getch();
_putch('*');
}
for (int i = 0; i < 5; i++) {
if (unos[i] != s[i]) {
n++;
cout << endl << "Your password is incorrect" << endl;
break;
} else if (i == 4) {
is_pwd_correct = true;
cout << endl << "Your password is correct" << endl;
}
}
} while (!is_pwd_correct && n < 3);
}
However I would recommend using string instead of char array, and do not use conio.h which is Windows only.
Also it would be a good idea to add handling of password size.
Browsing Internet, I read http://www.cplusplus.com/articles/E6vU7k9E/ .
Why not use the getch and getpass functions described there, with the main suggested, easier to read ?
int main()
{
string s = {'s','a','m','e','d'};
string unos;
int ntry (0);
bool ok (false);
while (!ok && (ntry < 3)) {
unos = getpass("Please enter the password: ",true);
if(unos==s) {
cout <<"Correct password"<<endl;
ok = true;
}
else {
if (ntry < 2) {
cout <<"Incorrect password. Try again"<<endl;
}
else {
cout << "access denied" << endl;
}
++ntry;
}
}
return 0;
}
The program takes in a word given by the user and translates that to pig latin. I've gotten everything to work almost perfectly, but have run into two bugs. The first of which is when translating words that begin with consonants say "count", the output is "ounttcay" instead of "ountcay". The second bug is that when for three letter words like "egg" or "not" the output is "egg_\377ay" or "ottn\377ay". Is there a simple way to remove that duplicate character and get rid of those numbers?
Note - Unfortunately it has to be done using a Cstring
#include <iostream>
#include <stdio.h>
#include <cstring>
using namespace std;
int convertToPigLatin(char arr[50]);
bool isVowel(char ch);
int main() {
char userInput[50];
char answer = ' ';
do {
cout << "Enter a word to convert it to pig latin" << endl;
cin.getline(userInput, 50); //get user input
cout << "Your entered word is " << userInput << endl;
convertToPigLatin(userInput); //translate user's input into piglatin
cout << "Would you like to convert another word?" << endl;
cin >> answer;
cin.ignore(); //clear past user input
cin.clear();
} while (answer == 'Y' || answer == 'y');
return 0;
}
bool isVowel (char ch) {
switch (tolower(ch)) { //if the first character of the given input is a vowel
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
return true;
default:
return false;
}
}
int convertToPigLatin(char arr[50]) {
char newArr[50];
// string conjunctions[6] = {"and","but","for","nor","yet","the"}; //list of conjunctions not to be converted
size_t arrLength = strlen(arr); //holds length of input
for (int i = 0; i < arrLength; i++) { //make sure all characters in input are lower case for easier processing
newArr[i] = tolower(arr[i]);
}
char lastChar = newArr[0]; //save the first character in case it needs to be appended
if (atoi(arr) || arr[0] == '\0') { //if the input contains a number or begins with a null character print an error
cout << "Cannot translate inputs that contain numbers" << endl;
return -1;
} else if (arrLength <= 2) { // if the input is 2 or less characters
cout << newArr << endl; //print the input as is
cout << "Boring! Try somthing more than 2 characters long" << endl;
return 0;
} else if ((strstr(newArr, "and") && arrLength == 3) || (arrLength == 3 && strstr(newArr, "but")) || (arrLength == 3 && strstr(newArr, "for")) || (arrLength == 3 && strstr(newArr, "nor")) || (arrLength == 3 && strstr(newArr, "yet")) || (arrLength == 3 && strstr(newArr, "the"))) { //if the input is more than 2 characters long
cout << newArr << endl; //print the input as is
cout << "No conjucntions try again!" << endl;
return 0;
} else { //if the given input is three characters and is not a conjunction, being translation
if (isVowel(arr[0])) { //check if input's first character is a vowel
cout << "Your word in piglatin is "<< strcat(newArr, "ay") << endl; //print that string with 'ay' at the end (i.e. egg'ay')
return 0;
} else { //else if the given input starts with a consonant
for (int r = 1; r < arrLength; r++) {
newArr[r-1] = newArr[r];
newArr[arrLength] = lastChar;
}
cout << "Your word in piglatin is " << strcat(newArr, "ay") << endl;
return 0;
}
}
return 0;
}
You're not terminating newArr, and the last index of the input string is arrLength - 1.
int convertToPigLatin(char arr[50]) {
// Make sure newArr is properly terminated.
char newArr[50] = {0};
// [...]
} else { //else if the given input starts with a consonant
for (int r = 1; r < arrLength; r++) {
newArr[r-1] = newArr[r];
}
// Do this outside the loop.
newArr[arrLength-1] = lastChar;
// No need for strcat here.
cout << "Your word in piglatin is " << newArr << "ay" << endl;
}
}
return 0;
}
You need to add the '\0' at the end of newArr because strlen does not count it so you are not copying it. strcat replaces '\0' witn 'ay\0' but you have no '\0'.
for (int r = 1; r < arrLength; r++) {
newArr[r-1] = newArr[r];
newArr[arrLength] = lastChar;
}
newArr[arrLength+1] = '\0';
cout << "Your word in piglatin is " << strcat(newArr, "ay") << endl;
Basically, this program allows a user to enter a sentence and depending on the users selection, it will show the middle character of the sentence, display it uppercase or lowercase, or backwards. Simple program, but I am new to programming so that may be the problem. I would like to figure out how to use loops instead of a ton of if statements. When I try to make some loops it breaks certain parts of the code but I am sure that is because I don't properly understand them. If you have any criticism or any advice on the code, I'd be happy to hear it. Thanks in advance!
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
int main()
{
int sel;
string sent;
bool validinput;
int i;
int x;
int j;
int a;
cout << "Welcome to my program. Enter a sentence and select one of the options below.\n";
cout << "Enter -999 to exit the program." << endl;
cout << "============================================================================" << endl;
cout << endl;
cout << "1. Display the middle character if there is one." << endl;
cout << "2. Convert to uppercase." << endl;
cout << "3. Convert to lowercase." << endl;
cout << "4. Display backwards." << endl;
cout << "Enter a sentence: ";
getline (cin, sent);
cout << "Selection: ";
cin >> sel;
if (sel < 1 && sel > 4)
{
cout << "Invalid input. Try again. Selection: ";
cin >> sel;
validinput = false;
}
else (sel >= 1 && sel <= 4);
{
validinput = true;
}
if (validinput == true)
{
if (sel == 1)
{
j = sent.length() / 2;
cout << "The middle character is: " << sent.at(j) << endl;
}
if (sel == 2)
{
for (int i = 0; i < sent.length(); i++)
{
if (sent.at(i) >= 'a' && sent.at(i) <= 'z')
{
sent.at(i) = sent.at(i) - 'a' + 'A';
}
}
cout << "Uppercase: " << sent << endl;
}
if (sel == 3)
{
for (int x = 0; x < sent.length(); x++)
{
if (sent.at(x) >= 'A' && sent.at(x) <= 'Z')
{
sent.at(x) = sent.at(x) - 'A' + 'a';
}
}
cout << "Lowercase: " << sent << endl;
}
if (sel == 4)
{
for (a = sent.length() - 1; a >= 0; a--)
{
cout << sent.at(a);
}
}
}
system("pause");
return 0;
}
Personally I would use the switch selection statement. I roughly did this just to explain a bit on how it can make your code more friendly and understandable.
int sel;
bool validInput = false;
switch(sel)
{
case 1:
//display middle char if there's one
case 2:
//convert to uppercase
case 3:
//convert to lowercase
case 4:
//display backwards
validInput = true;
break;
default: //if number does not meat 1, 2, 3 or 4
validInput = false;
break;
}
As you may notice, for case 1, case 2, case 3 and case 4, there's a break just to say that if the number is between 1 to 4; validInput is true.
Reference: Switch Selection Statement
i suggest using a switch. It will organize your code better. From looking at your code you seem to have used for and if wisely. But I suggest the if statements checking for the input be replaced with switch.
I'm trying to take user inputted notes and store them in an array. The validation works fine but when I input the last value in the loop I get:
Debug Assertion Failed!
Expression: "(_Ptr_user & (_BIG_ALLOCATION_ALIGNMENT - 1))==0"&&0
An invalid parameter was passed to a function that considers invalid parameters fatal.
I'm struggling to understand where the issue is and how I can fix it.
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
typedef string noteName;
noteName getNoteName(int i)
{
bool flag = true;
noteName Namein;
do
{
cout << "Please enter note name no. " << i + 1 << ": ";
cin >> Namein;
cout << "------------------------------------\n";
if (Namein.length() > 3 || Namein.length() < 2)
{
cout << "Sorry, a note name must be 2 or 3 characters long. Please try again.\n";
flag = false;
}
else if (Namein.length() == 3 && Namein[1] != '#')
{
cout << "Sorry, the second character of a sharp note name must be #. Please try again.\n";
flag = false;
}
else if ((Namein[0] < 'a' || Namein[0] > 'g') && (Namein[0] < 'A' || Namein[0] > 'G'))
{
cout << "Sorry, the first character of a note name must be a letter between A and G. Please try again.\n";
flag = false;
}
else if (isdigit(Namein.back()) == false)
{
cout << "Sorry, the last character of a note name must be a number. Please try again.\n";
flag = false;
}
else
{
flag = true;
}
} while (flag == false);
return Namein;
}
int main()
{
const int numNotes = 4;
noteName NoteNames[numNotes];
cout << "Hello\n";
for (int i = 0; i <= numNotes; i++)
{
NoteNames[i] = getNoteName(i);
}
cout << "Thank you, the note names and lengths you entered were: \n\n";
for (int i = 0; i <= numNotes; i++)
{
cout << i << ". " << NoteNames[i] << "\n";
}
cout << "Done!";
return 0;
}
I want to say it's something to do with getNoteName() having a string return type as I haven't had this issue with any of my other functions that return int.
noteName NoteNames[numNotes]; defines an array where NoteNames[numNotes - 1] is the largest element you can access.
You go one further than this. The behaviour on doing that is undefined which is manifesting itself as the crash that you observe.
Replace your loop limits with for (int i = 0; i < numNotes; i++), or similar.
(You also have your CamelCase conventions for class names and variable names switch round from what's normal, which makes your code confusing to read.)
(I'd also rather see constexpr int numNotes = 4;: Google that for more details.)
void offer_help();
bool play_one_game();
int main() {
offer_help();
play_one_game();
}
void offer_help() {
int help_response;
cout << "Need help? (0/1) ";
cin >> help_response;
if (help_response == 1)
cout << "I will generate a pattern of 4 numbers, each in the range 0 through 9.\n Each guess that you enter will be a line containing 4 integers,\n separated by spaces, such as:\n\t 2 4 7 1\n FOr each guess, I will echo back a lost consisting of\n 0's and 1's, with a 1 in a given position meaning that\n you guessed the number, and a zero meaning that you didn't.\n For example, if the actual solution was 2 3 6 1, I'll respond\n\t 1 0 0 1\n See how many guesses it takes you to get the solution!\n\n If you want to give up, type a negative number for one of\n your guesses, and we'll tell you what the pattern was.\n\n";
}
bool play_one_game() {
srand(time(0)); //needed to start randint
vector<int> solution; //vector of 4 randomly generated
//solutions
vector<int> guess; //vector containing user guesses.
vector<int> result;
int guess_input;
for(int i = 0; i < solution.size(); ++i)
solution[i] = randint(10);
int trial_number = 0; //int that shows what guess the user is on
while (play_one_game() == true) {
//ask user for inputs.
cout << "Guess #" << ++trial_number << "? ";
for (int i = 0; i < guess.size(); ++i){
cin >> guess_input;
guess.push_back(guess_input);
}
//outputs error if user inputs a letter.
if (!cin) {
cerr << "Bad input data! Feed me numbers!\n";
return 43;
}
if (cin < 0){
cout << "Too bad! Solution was " << endl;
for(int i = 0; i < result.size(); i++)
cout << (result[i]);
}
//determines if user correctly guessed any of the
//numbers and tells the user which is correct.
for (int i = 0; i < result.size(); i++) {
if (guess[i]==solution[i])
cout << 1 << " ";
else if (guess[i]!=solution[i])
cout << 0 << " ";
}
cout << endl;
// playagain();
cout << endl << "Play again (0/1)? ";
int replay;
cin >> replay;
if (replay == 0) {
play_one_game() == false;
return 5;
}
else if (replay == 1)
play_one_game() == true;
else {
cerr << "wat?\n";
return 10;
}
}
}
This is designed to allow a player to guess a pattern of random numbers.
No idea why I am getting a segmentation fault. The program is supposed to call the offer_help function, then the play_one_game function within main function. Then it should ask the player whether he wants to play again. If no, then bool play_one_game should be set to false and it should exit.
This is related to the play_one_game bool function.
You're getting a segmentation fault, because you end up in an endless recursion in the following line:
while (play_one_game() == true) {
play_one_game will call play_one_game in this line, and this will call play_one_game in the same line again. This will result in a stack overflow at last.
Better use some bool keepPlaying; and while(keepPlaying) instead.
EDIT: Well, this is a little bit more than a simple answer, but I like games, so... have a look at the following code:
#include <iostream>
#include <ctime>
#include <cstdlib>
#include <vector>
bool play_one_game();
void offer_help() {
int help_response;
std::cout << "Need help? (0/1) ";
std::cin >> help_response;
if (help_response == 1)
std::cout << "I will generate a pattern of 4 numbers, each in the range 0 through 9.\n"
"Each guess that you enter will be a line containing 4 integers,\n"
"separated by spaces, such as:\n"
"\t 2 4 7 1\n"
"For each guess, I will echo back a lost consisting of\n"
"0's and 1's, with a 1 in a given position meaning that\n"
"you guessed the number, and a zero meaning that you didn't.\n"
"For example, if the actual solution was 2 3 6 1, I'll respond\n"
"\t 1 0 0 1\n"
"See how many guesses it takes you to get the solution!\n\n"
"If you want to give up, type a negative number for one of\n"
"your guesses, and we'll tell you what the pattern was.\n\n";
}
int main() {
offer_help();
srand(time(0)); // Initialize random numbers with current time as seed
while(play_one_game()); // if play_one_game returns true, play again
}
bool play_one_game() {
std::vector<int> solution(4); // Four solutions for our guessing game
std::vector<int> guess; // User guesses
for(unsigned i = 0; i < solution.size(); ++i)
solution[i] = rand() % 10;
int trial_number = 0; //int that shows what guess the user is on
bool keepPlaying = true;
while(keepPlaying){
std::cout << "Guess #" << ++trial_number << "? ";
guess.clear(); // Clear old guesses
for(unsigned i = 0; i < solution.size(); ++i){
int guess_input;
//outputs error if user inputs a letter.
if (!(std::cin >> guess_input)) {
std::cerr << "Bad input data! Feed me numbers!\n";
std::cerr << "Try again!" << std::endl;
std::cin.clear(); // Clear flags
continue;
}
if (guess_input < 0){
std::cout << "Too bad! Solution was " << std::endl;
for(unsigned i = 0; i < solution.size(); i++)
std::cout << (solution[i]);
keepPlaying = false;
break;
}else
guess.push_back(guess_input);
}
if(!keepPlaying)
break;
if(solution.size() != guess.size()){
std::cerr << "Wrong number of guesses, try again!" << std::endl;
continue;
}
//determines if user correctly guessed any of the
//numbers and tells the user which is correct.
bool correct = true;
for (unsigned i = 0; i < solution.size(); i++) {
if (guess[i] == solution[i])
std::cout << 1 << " ";
else{
correct = false;
std::cout << 0 << " ";
}
}
if(correct){
std::cout << "Congratulations - you won!" << std::endl;
break;
}
std::cout << std::endl;
}
int replay = -1;
do{
// Ask user for input until input is 0 or 1
std::cout << std::endl << "Play again (0/1)? ";
std::cin >> replay;
}
while(replay != 0 && replay != 1);
return static_cast<bool>(replay); // return user replay answer (false/true)
}
Try to keep your code as simple as possible. Welcome to SO. And don't expect future answers to be that excessive.
You're never inserting anything into your solution vector. You just declare the vector, and then say:
for(int i = 0; i < solution.size(); ++i)
solution[i] = randint(10);
...which won't do anything since at this point solution.size() == 0. Later, when you iterate over your result vector, you end up accessing invalid elements in your empty solution vector. You also can't assume that the result vector and solution vector are the same size.