Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I keep ending up on a infinite loop even on do while loop!
What am I doing wrong? I tried everything but I still cant figure it it out. any help?
here is my code :
#include <iostream>
#include <string>
#include <Windows.h>
using namespace std;
//function prototypes
//prototype for IsAccessible
int IsAccessible(string username, string password);
//prototype for menu
void menu();
int main()
{
string username;
string password;
//make user to login
cout << "Enter username : ";
getline(cin, username);
cout << "\nEnter Password : ";
cin >> password;
IsAccessible(username, password);
cout << "Thank you for logging in!!";
cin.ignore();
cin.get();
return 0;
}
//function definitions
//definition for IsAccesible
int IsAccessible(string username, string password)
{
//check if user entered correct details
do
{
int x = 0;
if(password == "123" && username == "asdqw")
{
cout << "\n\nThank you for loggin in John!";
break;
}
//if user entered wrong details
else if(password != "123" && username != "asdqw")
{
cout << "\nYou have either entered a wrong password or username.\n";
cout << "Please retry.";
}
//if user exceeds limitation
if(x == 5)
{
cout << "\n\nYou have exceeded the 5 retry limitations......\n";
Sleep(4000);
cout << "Exiting program....";
Sleep(5000);
return 0;
}
}while(password != "123" && username != "asdqw");
return 0;
}
The while will keep looping until the username is not "asqdf" and the password is not "123" and the code never asks for a fresh username & password, so it will just keep looping to infinity. Also, you don't incrementx every time the loop iterates, so the 5-maximum-attempts code will never run.
Just a final tip - if your methods don't need to return, you can make the return type void. Instead of returning to exit the do-while, you could use a break statement.
Related
This question already has answers here:
Breaking out of an infinite loop
(2 answers)
do ... while loop not breaking c++
(2 answers)
Closed 6 months ago.
This post was edited and submitted for review 6 months ago and failed to reopen the post:
Duplicate This question has been answered, is not unique, and doesn’t differentiate itself from another question.
I'm just starting C++ and creating a simple password validation program. [edit] My goal is to display each messages if there is a lack of uppercase, lower case, digits, and/or special characters.
If there is only special character the output will be like this:
Enter your password: !
Password must contain a lower case!
Password must contain an upper case!
Password must contain a digit!
Enter your password:
what i want if all the requirements are met:
Enter your password: 1qQ+
your password is created
program is finished
But what i got is infinite loop of "your password is created".
Any solution or alternative to make my code better/efficient?
Sorry for bad intendation.
#include <iostream>
#include <string>
using namespace std;
void passcheck(string& password)
{
bool hasUpper = false, hasLower = false, hasDigit = false, hasSpecialchar = false;
for (int i = 0; i < password.length(); ++i)
{
if (islower(password[i]))
{
hasLower = true;
}
else if (isupper(password[i]))
{
hasUpper = true;
}
else if (isdigit(password[i]))
{
hasDigit = true;
}
else if (password.find(" !#$%&'()*+,-.:;<=>?#[]^_`{|}~"))
{
hasSpecialchar = true;
}
}
do
{
if (!hasLower)
{
cout << "Password must contain a lower case!"<< endl;
}
if (!hasUpper)
{
cout << "Password must contain an upper case!"<< endl;
}
if (!hasDigit)
{
cout << "Password must contain a digit!"<< endl;
}
if(!hasSpecialchar)
{
cout << "Password must contain special char!"<< endl;
}
else
{
cout << "your password is created" << endl;
}
}while(hasSpecialchar && hasDigit && hasLower && hasUpper);
}
int main(int argc, char const *argv[])
{
string password;
do{
cout << "Enter your password: ";
getline(cin, password);
passcheck(password);
}while(true);
cout << "program is finished" << endl;
cin.get();
return 0;
}
You want to execute the loop until all the boolean expressions are true I assume. This would evaluate to
do{
//your stuff
} while(!(hasSpecialchar && hasDigit && hasLower && hasUpper))`
But depending on what exactly you're trying to do there's probably a better approach then a do-while loop. Where do you set these booleans? If you're using a single thread, then this values aren't gonna change inside the loop and the whole loop doesn't make any sense.
you can use break keyword, like this
while (1) {
...
if (cond) {
break
}
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I'm trying to make a login page. When the program starts, the user has to type Guest and Password 1234 and he can edit his/her account. However, when I try to run it, it says:
Line 15 "Error incompatible types in assignment of 'const char[6]' to 'char[20]'
Line 16 "Error incompatible types in assignment of 'const char[5]' to 'char[20]'
I think it has to do with pointers but I am still a c++ newbie so I am having a hard time to understand pointers
#include <iostream>
#include <cstring>
#include <stdio.h>
#include <string.h>
using namespace std;
const int LINE_LENGTH=20;
const int ID_LENGTH=8;
struct profile{char user[20];char password[20];double CGPA; int ID;};
int main(){
int count=0, i;
profile student[10];
student[0].user="Guest"; //Line 15
student[0].password="1234"; //Line 15
char signupName[20];
char signupPassword[20];
while (count==0)
{
cout << "#############################################\n";
cout << " Welcome to my program! \n";
cout << " Sign up to get started \n\n\n";
cout << " If you are starting, use username 'Guest' \n";
cout << " and password '1234' \n\n";
cout << "Username: ";
cin >> signupName;
cout << "Password: ";
cin >> signupPassword;
cout << "#############################################\n";
for (i=0;i<11; i++)
{
if(strcmp(signupName,student[i].user)==0 && strcmp(student[i].password,signupPassword)==0)
{
count++;
}
}
if(count==0)
{
system("cls");
cout<<"Your username and/or password is incorrect\n";
}
}
system("cls");
}
You need two minor changes to your code! First, as Francois Andrieux says, you can't assign char array strings with = ...
// student[0].user = "Guest";
// student[0].password = "1234";
strcpy(student[0].user, "Guest");
strcpy(student[0].password, "1234");
Second, your for loop runs once to often:
// for (i = 0; i < 11; i++)
for (i = 0; i < 10; i++) // Note: The last element in an array of 10 is x[9]!
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I would like to improve the code below. I would like to use try-catch statement to validate the input letters. An error message should be printed in case the user inputs an invalid letter.
I have two methods: showMenu and selectOperation.
The methods:
//Show Operations in menu
void showMenu()
{
cout << " Select an option: \n\n"
<< "1 = Register new customers \n"
<< "2 = Register new products \n"
<< "3 = Add Product Existence \n"
<< "4 = Register a new purchase \n"
<< "0 = Exit \n\n";
}
//Select an Operation from menu
int selectOperation()
{
int selectedOperation = 0;
do
{
showMenu();
cin >> selectedOperation;
if ((selectedOperation < 0) || (selectedOperation > 4))
{
cout << "\n You have selected an invalid option"
<< "...Try again \n";
system("pause");
system("cls");
}
} while ((selectedOperation < 0) || (selectedOperation > 4));
return selectedOperation;
}
How should I do this?
You usually don't want to get and handle exceptions for invalid input.
Using exceptions to control regular flow of a program is a well known design flaw/anti pattern.
The idiomatic way is to check the input streams state:
// is true for non integer input and numbers outside the valid range
while(!(cin>>selectedOperation)) {
// Cleanup the stream state
cin.clear();
std::string dummy;
cin >> dummy; // Consume the invalid input
cout << "Please input a number." << std::endl;
}
The exception variant looks like this (way more complicated and less concise IMO):
cin.exceptions(std::ifstream::failbit);
bool validInput;
do {
try {
validInput = true;
cin>>selectedOperation)
}
catch (std::ios_base::failure &fail) {
validInput = false;
// Cleanup the stream state
cin.clear();
std::string dummy;
cin >> dummy; // Consume the invalid input
cout << "Please input a number." << std::endl;
}
} while (!validInput);
You have to clear the input stream in any way from fail() state.
You could also do this with a if else if statement...
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
Here's my problem: The program requires login info. The username verification works fine - when a bad username is given it is rejected and the user is asked to retry. However, when the password prompt appears, any given character is accepted - even just hitting the ENTER key will get you logged in. Can anyone spot my error??
int main()
{
int i;
int e;
string x;
string userName;
string userPass;
i = 1;
e = 1;
cout << "Please enter your information to login.\n";
//First 'do' is so that the line "Please enter your info..." does not get repeated
do
{
//This 'do' is to loop through the login process until successful
do
{
cout << "Username: ";
getline (cin, userName);
//Checks for a successfully input username
if (userName == "Fin")
{
cout << "Password: ";
getline (cin, userPass);
//Checks for a successfully input password
// HERE'S WHERE THE PROBLEM IS
if (userPass == "fin123");
{
cout << "Login successful.\n" << "Press ENTER to exit.";
//Waits for user to hit the ENTER key before exiting
getline (cin, x);
if (x.empty())
{
return 0;
}
}
//If the password is incorrect, start the login loop over
if (userPass != "financiero123")
{
cout << "Incorrect password. Please try again.";
//Waits for user to press a key before starting over
cin.get();
e = 0;
}
}
//If the username is incorrect, start the login loop over
if (userName != "Financiero")
{
cout << "Incorrect username. Please try again.";
//Waits for user to press a key before starting over
cin.get();
e = 0;
}
} while (e != 0);
e = 1;
} while (e != 0);
return 0;
}
if (userPass == "fin123");
{
// ...
The semicolon after the conditional closes the conditional, so what is left becomes an anonymous block. It's as though you had written this:
if (userPass == "fin123") { }
{
// ...
Therefore the block following this line is executed unconditionally.
Remove the semicolon to correct the logic error.
(Compiling with the -Wempty-body flag would have warned about this.)
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I'm just a beginner and trying out some code that my teacher taught us to use and things from the textbook.
This program is designed to be for the user to enter in their name and enter in the password as what the system asks them to put down.
Can somebody explain to me why this loop keeps looping itself infinitely when else is triggered?
Also, what does the cin.ignore do to the memory of the char name? Why is 80 better than 20?
AND, why aren't the random numbers actually random? Every time I run it, the numbers are the same.
Thank you all so much!
#include <iostream>
#include <cstdlib>
using namespace std;
int main ()
{
char name[20];
int pwd, rand1, rand2;
for (int i=0;i<1; i++)
{
cout<<"Name: ";
cin.get(name, 20);
cin.ignore(80, '\n');
cout<<endl;
srand(rand() % 1000);
rand1 = (rand() % 21);
rand2 = (rand()%6);
cout<<"Password: "<<rand1<<"*"<<rand2<<"= ";
cin>>pwd;
if(pwd == rand1*rand2)
{
cout<<endl<<"Welcome to our main page, "<<name<<"."<<endl;
}
else
{
cout<<"Wrong password, type again." <<endl;
i--;
}
}
return 0;
}
First up formatting of code will help you understand better.
Also avoid using namespace std, its bad practice and clutters the global scope with names. Instead use using std::xxxx if you dont want to write std::cout, std::cin, etc every time.
Reformatted code:
#include <iostream>
#include <cstdlib>
using std::cin;
using std::cout;
using std::endl;
int main ()
{
char name[20];
int pwd, rand1, rand2;
for (int i = 0; i < 1; i++) {
cout << "Name: ";
cin.get(name, 20);
cin.ignore();
cout << endl;
srand(rand() % 1000);
rand1 = (rand() % 21);
rand2 = (rand() % 6);
cout << "Password: " << rand1 << "*" << rand2 << "= ";
cin >> pwd;
cin.ignore();
if(pwd == rand1*rand2) {
cout << endl << "Welcome to our main page, " << name << "." << endl;
} else {
cout << "Wrong password, type again." << endl;
i--;
}
}
return 0;
}
Secondly as you can see in the above code the line cin.ignore(); has been added after cin >> pwd. Before your code was getting cin >> name, leaving '\n' in the input, ignoring '\n', getting cin >> pwd, leaving '\n' in input, looping and reading input as empty with a '\n', leaving another '\n' in input, first '\n' is removed by ci.ignore(), second '\n' read by cin >> pwd, ... etc. Or at least this is how I understand it.
Somebody has answered the first question:Because when you i--, the i in the for loop keeps decreasing and then increasing.-By Gasim
Then, if your input is longer than 20, the program may stop. So you need cin.ignore(80, '\n') to ignore the excess input. The number 80 is just a big number. You can replace it with another number-only if it's big enough.
You are supposed to use srand with time. srand(time(null)) may help.