I am a beginner in C++ and I was doing a do/while loop exercise and I am having trouble with it recognising the condition let alone it not looping properly. Can you guys give me a good foundation on how a simple problem like this is solved? I want to try and use a string to fulfill the condition of the do/while loop.
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main ()
{
double mean = 0;
string continuer;
do
{
cout << "Do you want to proceed?" << endl;
getline (cin, continuer);
cout << "something" << endl;
cin >> mean;
}
while (continuer == "Y" || continuer == "y");
return 0;
}
What I gather from your question and comment, you want to iterate through the loop at user's will.
You just want a char variable for that, like this.
string input ;
int number = 0 ;
do
{
cout << "Please enter a number" << endl ;
cin >> number ;
cout << "If you want to continue, Press Y" << endl ;
cin >> input ;
} while (input == "Y" || input == "y") ;
This do-while loop will execute at least one time, because the condition gets checked at the end of the loop execution. So even if the user does not press Y when asked the first time, this loop would have been executed once. After that, it will go on as long as the condition is fulfilled.
Learn more about the do-while loop here.
http://www.cplusplus.com/doc/tutorial/control/
What do you see? The body of the loop should be executed at least once. Does that happen?
Also, Continuer can be longer than one character, for instance "Y\n". Do test for that.
Here is what I would do:
#include <string>
#include <sstream>
using namespace std;
int main ()
{
double number = 0;
string continuer;
int loop = 0
do
{
cout << "Do you want to proceed?" << endl;
getline (cin, number);
cout << "something" << endl;
cin>> mean;
getline (cin, continuer);
cout << "Your answer was '" << continuer << "'." << endl;
loop = strcmp("Y", continuer);
if (loop != 0) strcmp("y", continuer);
if (loop == 0) cout << "Your choice is to stop." << endl;
else cout << "Your choice is to continue." << endl;
} while (loop == 0);
cout << "Bye" << endl;
return 0;
}
Be as explicit as you can untill you are confident enough in the language and the algorithm you are working with. It is easier to see what is happening and when it works it is easy to remove the 'cout' lines.
Related
I want the user to choose between playing the game again or ending the program, however when prompted, if they press 'y' the same thing gets repeated over and over instead of the whole program from the very beginning. I've tried while loops, do/while loops, if statements, rearranging the code, but nothing has worked. Any advice?
#include <iostream>
#include <string>
using namespace std;
int main(){
string animal = "fish";
string guess;
char choose = 'Y' ;
int count = 0;//keeps a running total of how many times the user
has guessed an answer.
int limit = 5;//allows user to guess only 5 times, otherwise
they loose the game.
bool out_of_guesses = false;//to check whether the user has run
out of guesses.
cout << "I am thinking of an animal.\n" << endl;
do{
while(animal != guess && !out_of_guesses){//Nested while
loop inside main loop to keep track of how many tries the user has
attempted and to validate their answers.
if(count < limit){
cout << "Can you guess what animal I am thinking of?: ";
getline(cin, guess);
count++;
if(animal != guess){
cout << "\nHmm, nope. That's not the animal I'm
thinking of." << endl;
if(count > 2 && count <5){
cout << "I'll give you a hint. It lives in
water." << endl;
}
}
}
else{
out_of_guesses = true;
}
}//End nested while loop
if(out_of_guesses){
cout << "\nI'm sorry, but you are out of guesses." <<
endl;
}
else{
cout << "\n*** Good job! You guessed the correct animal!
***" << endl;
cout << "\t\t><)))º> ❤ <º)))><\t\t" << endl;
}
//The do-while loop is there to ask the user if they wish to
play the game again.
cout << "Would you like to try again?(y/n): ";
cin >> choose;
if(choose == 'N' || choose == 'n')
break;
}while(choose == 'Y' || choose == 'y');
return 0;
}
The bool out_of_guesses = false; must be in-between while(true) and while(animal != guess && !out_of_guesses), and not outside the first while loop. Because our while loop condition is always false, and then it does enter it.
You should also reset your guess variable in-between those 2 loops, else same thing could happen (false while loop) in case of the answer is found.
Here the code with some refactoring/review, which I used the guess as upper case to handle any typography of the answer. I also removed the out of guess variable to use the count and limit one instead.
#include <iostream>
#include <string>
#include <cctype>
int main()
{
const std::string animal = "FISH";
const int limit = 5;
do
{
std::cout << "I am thinking of an animal.\n";
int count = 0;
std::string guess;
while(animal.compare(std::toupper(guess)) != 0 && count < limit)
{
std::cout << "Can you guess what animal I am thinking of?: \n";
std::cin >> guess;
count++;
if(animal.compare(std::toupper(guess)) != 0)
{
std::cout << "\nHmm, nope. That's not the animal I'm thinking of.\n";
if(count > 2)
{
std::cout << "I'll give you a hint. It lives in water.\n";
}
}
}
}//End nested while loop
if(count >= limit)
{
std::cout << "\nI'm sorry, but you are out of guesses.\n";
}
else
{
std::cout << "\n*** Good job! You guessed the correct animal! ***\n";
std::cout << "\t\t><)))º> ❤ <º)))><\t\t\n";
}
char choose = 'Y' ;
std::cout << "Would you like to try again?(y/n): ";
std::cin >> choose;
if(std::toupper(choose) == 'N') break;
} while(true);
return 0;
}
I just can't seem to get this program to work properly. I can get it to accept two integers and print them to the screen. But I can't get the program to terminate when the '|' is used. Once that its entered it loops infinitely. Here is the code that I have so far:
#include "../../std_lib_facilities.h"
int main()
{
int num1 = 0;
int num2 = 0;
char counter = '\0';
cout << "Please enter two integers and press enter. \n";
bool test = true;
while (counter != '|')
{
cin >> num1 >> num2;
cout << "Your numbers are: " << num1 << " " << num2 << endl;
if (cin.fail())
{
cout << "Goodbye!\n";
test = false;
}
else (counter != '|');
cout << "Enter more numbers or press '|' to exit.\n";
}
system("pause");
}
You are using the wrong condition in your while loop. You are never changing counter so the loop will never end. However you do change test to false in the while loop if the input fails. You can change the condition of the while loop to use test instead like
while(test)
{
//...
}
Since counter is no longer being used you can get rid of it completely.
Please note that unless you change to taking in string and parsing the input any input that will cause cin to fail will end the loop not just a |.
The purpose of the conditional statement is to print out a simple text based menu and then store input from the user as well as evaluate this to the condition of a loop.
If the condition was not meet, the user should be prompted to enter in a int number, that would result in the condition being true. Instead it just exits the loop.
I have tried both while and now, if loops to accomplish the task.
Here is the Code:
#include "stdafx.h"
// Namespaces
using std::cin;
using std::cout;
using std::endl;
using std::istream;
using std::iostream;
using std::ostream;
using std::string;
// Variables
const string new_game = "Start a new game";
const string continue_game = "Continue your game";
const string load_save = "Load a save";
int menu_choice = 0;
const string choice_description = "You choice to";
// MAIN Program
int _tmain(int argc, _TCHAR* argv[])
{
cout << "Welcome to The Forgotten Time" <<endl;
cout << "You have the following options" << endl;
while (menu_choice < 1 || menu_choice > 3 )
{
cout << "1." << new_game << endl;
cout << "2." << continue_game << endl;
cout << "3." << load_save << endl;
cin >> menu_choice;
}
switch (menu_choice)
{
case 1: cout << choice_description << new_game;
case 2: cout << choice_description << continue_game;
case 3: cout << choice_description << choice_description;
}
cin.ignore();
cin.get();
return 0;
}
In the end i would like to be able to combine the conditional statement in a function
and pass it through a switch statement in order to create a sentence, that evaluates the
users input and displays their choice.
Initially you set:
int menu_choice = 0;
Then you ask:
if (menu_choice < 1 || menu_choice > 4 )
The choice is smaller than 1 so the if block is entered.
You then get some user input and exit the application.
You have no loop in your code at all. Just an initial conditional statement that would return a true value because:
menu_choice=0;
and,
if(menu_choice<1 ||...)
You don't need a "return" statement, either. Put in a switch() after your if().
Also, you could just remove the second if() condition and put your whole main() content in a while() or do..while() loop.
Also, a switch is pretty efficient if you have a menu based display that takes in certain specific discrete-set of values.
Remove your if condition, instead use a do while loop.
do{
cout << "1." << new_game << endl;
cout << "2." << continue_game << endl;
cout << "3." << load_save << endl;
cin >> menu_choice;
}
while (menu_choice!=0);
I'm trying to get the user to input their name(s) using a while loop with an array and cin, but after the last person's name is input, the program crashes instead of moving on. Is there a way to fix this, or do I need to completely change up the code? I'm also fairly new to c++, so can any answers be given as simply as possible?
#include <iostream>
#include <string>
using namespace std;
int main()
{
unsigned int numberofplayers;
number://loop back here if more than 4 players
cout << "Number of players: ";
cin >> numberofplayers;
if(numberofplayers > 4 || numberofplayers < 1){
cout << "Invalid number, please enter a number from 1 to 4." << endl;
goto number;
}
string name[numberofplayers];
cout << "Enter your name" << endl;
int a = 1;
while(a < numberofplayers + 1){
cout << "Player " << a << ": ";
cin >> name[a];
cout << "Hello, " << name[a] << "." << endl;
a++;
}
}
You would probably facing array index out of bound, so Change you while loop to this and set a=0 to fill from 0th index.
while(a < numberofplayers){
}
Your last iteration exceeds the size of the array. You need to change it to
while(a < numberofplayers)
also, on another note, the keyword goto isn't used much anymore. I would suggest using a while there also like
while(true){
cout<<"number of players";
cin>>numberofplayers
if(numberofplayers is valid input){
break;
}
cout<<"bad input";
}
There is a question on stackoverflow discussing the use of goto extensively here:
GOTO still considered harmful?
Ok, I've been learning C++ for about 4 days now and it's my first programming language. So what this really means is that I've only got about 8 hours of programming experience and a lot of that was reading the intro to my C++ book and figuring out how to use XCode.
Anyway, my beginner C++ book is asking me to do the following: "Write a password prompt that gives a user only a certain number of password entry attempts so that the user cannot easily write a password cracker."
The only thing is I just now learned loops and I don't think the book has even covered how to limit attempts yet. Can anyone help? I've seen this, but it's too advanced for me and I don't get it. Here's the code: (really basic newb code... sorry if it insults your intelligence)
#include <iostream>
#include <string>
using namespace std;
int main ()
{
string username;
string password;
while ( 1 )
{
cout << "Enter your username: " << endl;
cin >> username;
cout << "Enter your password: " << endl;
cin >> password;
if ( username != "billy" && password != "bob" )
{
cout << "Incorrect username/password combination. Please try again." << "\n" <<
endl;
}
else
{
break;
}
}
cout << "Access granted." << endl;
}
The while ( 1 ) { } construct repeats whatever is inside the {} to infinity, unless you explicitly break from the loop. That's a loop, btw.
How could you break from it after a number of attempts? You could have a counter that gets incremented with every attempt and break from the loop at the limit:
if ( ++counter >= limit )
break;
or simply move the condition inside the while
while ( ++counter < limit )
or use a simple for loop or a do {} while().
Take some variable, say attemptCount, which keeps track of number of attempts made. Initialize it to 0 and increment it by 1 with every unsuccessful attempt. Put the condition in while loop checking that the attemptCount is less than the number of allowed attempts (taken 3 in my code below). So, the code will be:
#include <iostream>
#include <string>
using namespace std;
int main ()
{
string username;
string password;
int attemptCount = 0;
while ( attemptCount < 3 )
{
cout << "Enter your username: " << endl;
cin >> username;
cout << "Enter your password: " << endl;
cin >> password;
if ( username != "billy" && password != "bob" )
{
cout << "Incorrect username/password combination. Please try again." << "\n" <<
endl;
attemptCount++;
}
else
{
break;
}
}
cout << "Access granted." << endl;
}
Think about how this works:
#include <iostream>
using namespace std;
int main()
{
const int MAXTRYS = 4;
int numTrys = 0;
while(numTrys != MAXTRYS)
{
cout << "Attempting login" << endl;
++numTrys;
}
return 0;
}
Your while(1) loop will go on forever unless you also have some counter that you increment with every failed attempt.
But frankly...why have a while loop and a separate counter? You have a known max number of iterations; that's the kind of case a for loop was made for.
for (int attempts = 1; attempts <= 3; ++attempts) {
... get login info ...
if (...username and password are correct...) {
cout << "Access granted.\n";
return 0;
}
else {
cout << "Invalid login.\n";
}
}
// Note as well, the default case (what happens if they make it through the loop)
// should be no access. Otherwise, someone could just succeed by inputting three
// bad passwords. :P
cout << "Too many invalid login attempts.\nExiting.\n";
return -1;
You should use a for loop, not a while loop then. Something along the lines of:
bool bSuccess = false;
for (int i = 0 ; i < maxAttemps ; ++i)
{
// your stuff
// set bSuccess = true when relevant
}
if (bSuccess)
{
// ok, successfully logged in
}
Infinite loops are often restricted to really infinite loops (waiting for network messages forever until quit, etc.). As a rule of thumb for good practice, try to avoid infinite loops as much as possible, and break constructs too because it's kind of hacky generally. To exercise, you should try to write nice code which translates to an easy dataflow.
I guess you suspect it, but this wouldn't be secure at all (you store username and password in plain text in the code of your executable).
I`m having a hard time re-familiarizing with C++, since highschool ( #8 years ago ) alot has changed, or my informathics teacher was just bad...
I also find the "for" loop better for this kind of exercise but isn't it true that "return 0;" and "break;" do the same thing?
This is what I worked out with what I saw here and what I already "knew" :). Works like a charm.
#include <iostream>
#include <string>
using namespace std;
int main ()
{
int attempts = 0;
string password;
for (int attempts = 0; attempts < 5; ++attempts )
{
cout << "enter your password! \n";
cin >> password;
++attempts;
if ( password == "boo123" )
{
cout << "granted!";
return 0;
}
else
{
cout << "denied! \n";
}
}
}
and 1 more thing: all loops are infinite 'till you "break;" it or "return 0;" it...
/*Write a password prompt that gives a user only a certain number of password entry attempts—
so that the user cannot easily write a password cracker*/
#include <iostream>
#include <string>
using namespace std;
int main ()
{
string password;
int x = 1;
while (1) //This creates an overall top level infinite loop
{
cout << "Input password here: ";
cin >> password;
if ( password == "teddy") //This sets the condition for success
{
cout << "Access Granted!!!!";
break; //The break is applied here to stop the cycle after success is made
}
else if ( password != "teddy") //This sets the condition for failure
{
cout << "Wrong username/password" << "\n" << x << " " << "wrong attempts" << "\n";
++x;
if ( x > 5 ) // This is the counter limit portion. Limit set to 5 attempts
{
break;
}
}
}
}
#include <iostream>
using namespace std;
int main()
{
string password;
int pCounter = 0;
cout << "Enter Password here: ";
getline(cin, password);
while(pCounter <= 4){
if(password != "winner"){
cout << "Count: " << pCounter << endl;
cout << "Try again..wrong entry.." << endl;
cout << "Enter Password here: ";
getline(cin, password);
++pCounter;
if((password != "winner") && (pCounter == 4)){
cout << "The End..No more tries!!" << endl;
break;
}
}
else{
cout << "Welcome In Bro" << endl;
break;
}
}
return 0;
}
include
using namespace std;
int main() {
string password = "set"; //declaring the password
string input; //declaring a string for input later
for (int attempt = 1; attempt <= 3; attempt++) { //if you fail the password 3 times you get kicked out
cout << "enter password " << flush;
cin >> input;
if (input == password) { //checks to make sure the user input matches set password
cout << "granted";
return 0; //once correct password is put in the program ends
}
else { //if password is wrong repeat till right or 3 trys
cout << "you fail" << endl;
}
}
}