This is my first simple program. It keeps printing out Guess what it is. non-stop and doesn't even ask for user input. (the next line of code.)
What is my mistake?
#include <iostream>
#include <string>
using namespace std;
int main()
{
string userName;
cout << "Hello there.\n";
cout << "My name is TARS. \n";
cout << "What is your name? \n";
getline(std::cin, userName);
cout << userName << ", let's play a game.\n";
int secretNum;
secretNum = rand() % 20 + 1;
cout << "I'm thinking of a number between 1-20.\n";
int Guess;
bool conti = true;
while (conti)
cout << "Guess what it is. \n";
cin >> Guess;
if (Guess == secretNum)
{
cout << "You read my mind!";
conti = false;
}
if (Guess < secretNum)
{
cout << "That is too low.";
}
if (Guess > secretNum)
{
cout << "That is too high.";
}
return 0;
}
You need to use brackets
#include <iostream>
#include <string>
using namespace std;
int main()
{
string userName;
cout << "Hello there.\n";
cout << "My name is TARS. \n";
cout << "What is your name? \n";
getline(std::cin, userName);
cout << userName << ", let's play a game.\n";
int secretNum;
secretNum = rand() % 20 + 1;
cout << "I'm thinking of a number between 1-20.\n";
int Guess;
bool conti = true;
while (conti)
{
cout << "Guess what it is. \n";
cin >> Guess;
if (Guess == secretNum)
{
cout << "You read my mind!";
conti = false;
}
if (Guess < secretNum)
{
cout << "That is too low.";
}
if (Guess > secretNum)
{
cout << "That is too high.";
}
}
return 0;
}
By default if you don't use them only the next line will be considered part of the while loop
in your case:
while (conti)
cout << "Guess what it is. \n";
you need braces for the while loop, or it will execute just that single statement forever.
while (conti)
cout << "Guess what it is. \n";
is equivalent to:
while (conti)
{
cout << "Guess what it is. \n";
}
i.e. the loop ends there. What you need is provide the opening and closing braces for the loop at the right place.
while (conti)
{
cout << "Guess what it is. \n";
cin >> Guess;
if (Guess == secretNum)
{
cout << "You read my mind!";
conti = false;
}
if (Guess < secretNum)
{
cout << "That is too low.";
}
if (Guess > secretNum)
{
cout << "That is too high.";
}
}
You have missed the braces for while loop. You may try this:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string userName;
cout << "Hello there.\n";
cout << "My name is TARS. \n";
cout << "What is your name? \n";
getline(std::cin, userName);
cout << userName << ", let's play a game.\n";
int secretNum;
secretNum = rand() % 20 + 1;
cout << "I'm thinking of a number between 1-20.\n";
int Guess;
bool conti = true;
while (conti){
cout << "Guess what it is. \n";
cin >> Guess;
if (Guess == secretNum)
{
cout << "You read my mind!";
conti = false;
}
if (Guess < secretNum)
{
cout << "That is too low.";
}
if (Guess > secretNum)
{
cout << "That is too high.";
}
}
return 0;
}
You're missing two curly braces to widen the scope of your while-loop. Note that without curly braces the scope of any loop in C++ will stop at the first semicolon. Here's a working solution:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string userName;
cout << "Hello there.\n";
cout << "My name is TARS. \n";
cout << "What is your name? \n";
getline(std::cin, userName);
cout << userName << ", let's play a game.\n";
int secretNum;
secretNum = rand() % 20 + 1;
cout << "I'm thinking of a number between 1-20.\n";
int Guess;
bool conti = true;
while (conti)
{ // <-- This curly brace was missing
cout << "Guess what it is. \n";
cin >> Guess;
if (Guess == secretNum)
{
cout << "You read my mind!";
conti = false;
}
if (Guess < secretNum)
{
cout << "That is too low.";
}
if (Guess > secretNum)
{
cout << "That is too high.";
}
} // <-- This curly brace was also missing
return 0;
}
Related
#include <iostream>
using namespace std;
bool play_game(int n) {
int guess;
bool noguesses = false;
int numofguesses = 0;
cout << "Welcome to my number guessing game\n";
while (n!=guess && !noguesses)
{
if (numofguesses < 6)
{
cout << "\n";
cout << "Enter your guess: ";
cin >> guess;
cout << "\n";
cout << "You entered: " << guess;
numofguesses++;
return false;
}
else
{
oog = true;
}
}
if (noguesses) {
cout << "I'm sorry. You didn't find my number.\n";
cout << "It was" << n << endl;
}
else
{
cout << "\n";
cout << "You found it in" << numofguesses << "guess(es)\n";
return true;
}
}
int main()
{
int secretnum = 5;
play_game(secretnum);
}
When I run this, the program stops after cout << "You entered: " << guess;. I want it to keep looping until the number of guesses reaches 6, or until the user inputs the correct answer.
Remove return false;
if (numofguesses < 6)
{
cout << "\n";
cout << "Enter your guess: ";
cin >> guess;
cout << "\n";
cout << "You entered: " << guess;
numofguesses++;
return false; //Remove this line
}
I am just studying so don't judge me hard please.
I have a problem. I know how to do a do-while loop. But today I have learned about functions. So I made do-while loops in functions and they are looping infinitely. How do I stop the loops?
#include <iostream>
using namespace std;
void text()
{
cout << "Log in to see the Menu. " << endl;
}
void lg()
{
const string login = "el1oz";
string input;
cout << "Login > " << flush;
cin >> input;
do{
if(login == input){
break;
}
else{
cout << "Try again." << endl;
}
}while(true);
cout << "Correct Login! " << endl;
}
void pw()
{
const string password = "Mau01171995";
string input1;
cout << "Password > " << flush;
cin >> input1;
do{
if(password == input1){
break;
}
else{
cout << "Try again. " << endl;
}
}while(true);
cout << "Correct Passsword! " << endl;
}
int main()
{
text();
lg();
pw();
return 0;
}
You're not changing input after the code enters in the loop. You should put the cin >> input inside the loop.
Also consider when to use a while loop vs a do while loop. In this case a while loop is better.
You probably should not use using namespace std; (More information here).
You should use more descriptive names.
#include <iostream>
using std::cin;
using std::string;
using std::cout;
using std::flush;
using std::endl;
void printWelcome()
{
cout << "Log in to see the Menu. " << endl;
}
void inputUser()
{
const string login = "el1oz";
string input;
cout << "Login > " << flush;
while(cin >> input){
if(login == input){
break;
}
else{
cout << "Try again." << endl;
}
}
cout << "Correct Login! " << endl;
}
void inputPassword()
{
const string password = "Mau01171995";
string input;
cout << "Password > " << flush;
while(cin >> input){
if(password == input){
break;
}
else{
cout << "Try again. " << endl;
}
}
cout << "Correct Passsword! " << endl;
}
int main()
{
printWelcome();
inputUser();
inputPpassword();
return 0;
}
I am making a simple guess the number game using C++.
My program checks if the user input is an integer or not.
But when I input for example "abc" the program keeps saying: "Input a number!" instead of saying it once and let the user input something again..
Code:
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int chances = 3;
void ask();
void checkAnswer(int ans);
void defineNumber();
int correctAnswer;
void defineNumber(){
srand(time(0));
correctAnswer = rand()%11;
}
void checkAnswer(int ans){
if(ans == correctAnswer){
cout << "The answer was right!\n" << endl;
exit(0);
}else{
if(chances > 0){
cout << "Wrong answer, try again!\n" << endl;
chances--;
ask();
}else{
cout << "You lost!" << endl;
exit(0);
}
}
}
void ask(){
int input;
cout << correctAnswer << endl;
try{
cin >> input;
if(input > 11 || input < 0){
if(!cin){
cout << "Input a number!" << endl; //HERE LIES THE PROBLEM
cin.clear(); //I TRIED THIS BUT DIDN'T WORK AS WELL
ask();
}else{
cout << "Under 10 you idiot!" << endl;
ask();
}
}else{
checkAnswer(input);
}
}catch(exception e){
cout << "An unexpected error occurred!" << endl;
ask();
}
}
int main(){
cout << "Welcome to guess the number!" << endl;
cout << "Guess the number under 10: ";
defineNumber();
ask();
}
Thanks in advance.
Try this:
try{
cin >> input;
if (cin.good()) {
if(input > 11 || input < 0) {
cout << "Under 10 you idiot!" << endl;
ask();
} else {
checkAnswer(input);
}
} else {
cout << "Input a number!" << endl;
cin.clear();
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
ask();
}
}catch(exception e){
cout << "An unexpected error occurred!" << endl;
ask();
}
and don't forget to use this at the beginning: #include <climits>
The cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); line will ignore everything until the next int number.. Therefore it will not loop anymore..
well its a simple project it does everything as it should minus it wont exit when it is suppose to.
I have tried many different ways including goto statements I tried a if loop but got nothing but errors. The current code gives no errors just I dont know where to go to make it exit. It doesnt have to be fancy this is only my second program
// C// Guess My Number
// The classic number guessing game
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
srand(static_cast<unsigned int>(time(0))); //seed random number generator
int secretNumberE = rand() % 10 + 1;
int secretNumberM = rand() % 100 + 1;// random number between 1 and 100
int secretNumberH = rand() % 1000 + 1;
int tries = 0;
int guess;
char play;
{
cout << "\tWelcome to Guess My Number\n\n";
START:
cout << "Difficulty Levels\n\n";
cout << "1 - Easy\n";
cout << "2 - Normal\n";
cout << "3 - Hard\n\n";
int choice;
cout << "Choice: ";
cin >> choice;
switch (choice)
{
case 1:
cout << "You picked Easy.\n";
do
{
cout << "Enter a guess 1-10: ";
cin >> guess;
++tries;
if (guess > secretNumberE)
{
cout << "Too high!\n\n";
}
else if (guess < secretNumberE)
{
cout << "Too low!\n\n";
}
else
{
cout << "\nThat's it! You got it in " << tries << " guesses!\n";
}
} while (guess != secretNumberE);
std::cout << "Do you want to play again y/n? ";
cin >> play;
if ( play = 'y' ){
goto START;
}
else if (play = 'n')
{
cout << " Thank you for playing. ";
return 0;
}
break;
case 2:
cout << "You picked Normal.\n";
do
{
cout << "Enter a guess 1-100: ";
cin >> guess;
++tries;
if (guess > secretNumberM)
{
cout << "Too high!\n\n";
}
else if (guess < secretNumberM)
{
cout << "Too low!\n\n";
}
else
{
cout << "\nThat's it! You got it in " << tries << " guesses!\n";
}
} while (guess != secretNumberM);
std::cout << "Do you want to play again y/n? ";
cin >> play;
if ( play = 'y' ){
goto START;
}
else if (play = 'n')
{
cout << " Thank you for playing. ";
return 0;
}
break;
case 3:
cout << "You picked Hard.\n";
do
{
cout << "Enter a guess 1-10: ";
cin >> guess;
++tries;
if (guess > secretNumberH)
{
cout << "Too high!\n\n";
}
else if (guess < secretNumberH)
{
cout << "Too low!\n\n";
}
else
{
cout << "\nThat's it! You got it in " << tries << " guesses!\n";
}
} while (guess != secretNumberH);
std::cout << "Do you want to play again y/n? ";
cin >> play;
if ( play = 'y' ){
goto START;
}
else if (play = 'n')
{
cout << " Thank you for playing. ";
return 0;
}
break;
default:
cout << "You made an illegal choice.\n";
goto START;
return 0;
}}}
if ( play = 'y' ){
goto START;
}
else if (play = 'n')
{
cout << " Thank you for playing. ";
return 0;
}
The first if will always be true, because you are using the assignment operator rather than the equality operator. You need to use == to compare two values.
...
char play;
{
...
There seems to be an extra { in your code that you are wrapping your stuff with.
Things that are clear to me that you need to work on, indentation. There is probably an auto-format shortcut in your IDE. Start using that. It's impossible to read your code well this will lead to a bunch of errors in the long run for simple things that you will be banging your head over.
goto highly recommend not using this unless you know what your doing.
Start learning functions/methods they will save your life and overall improve you workflow.
and you can replace goto with it.
example of a function..
int startGame(){
cout << "Difficulty Levels\n\n";
cout << "1 - Easy\n";
cout << "2 - Normal\n";
cout << "3 - Hard\n\n";
int choice = 0;
cout << "Choice: ";
cin >> choice;
return choice;
}
Other things.
if ( play = 'y' ) needs to be if ( play == 'y' ) rinse repeat this because you are trying to check for equality(conditional) not setting a value which is what one = does.
Also, ALWAYS INITIALIZE VALUES int choice; should be int choice = 0; or some default value.
use the "break" keywork
do
{
if(mycondition)
{
break;
}
} while (loopCondition);
I am struggling to get an input validation working for my game.
#include <iostream>
#include <ctime>
using namespace std;
int main()
{
int iGumballs;
int iUserguess;
int iGuesses = 0;
while (true)
{
system("CLS");
cin.clear();
iGuesses = 0;
srand(static_cast<unsigned int>(time(0)));
iGumballs = rand()%1000+1;
cout << "How many gumballs are in the bumball jar? You guess! 1-1000" << endl;
do
{
cout << "Enter your guess: ";
cin >> iUserguess;
if(iUserguess > iGumballs)
{
cout << "Too high!" << endl << endl;
}
if(iUserguess < iGumballs)
{
cout << "Too low!" << endl << endl;
}
iGuesses ++;
}
while(iUserguess > iGumballs || iUserguess < iGumballs);
cout << "You guessed the right amout of gumballs" << endl << endl;
cout << "You took " << iGuesses << " guesses" << endl << endl;
system ("pause");
}
return 0;
}
I basically want the program to display
Your Guess: Sorry, incorrect input - try again
When the user enters a number less then 1, and higher then 1000, as well as some sort of validation which makes sure a number is entered instead of a letter or symbol. I tried cin.fail() but I couldn't get it quite to work.
Thanks,
John
You will need some test to see if is a number or not, try this:
#include <iostream>
#include <string>
#include <ctime>
#include <boost/lexical_cast.hpp> //dependency that can be optional
using namespace std;
bool is_number(const std::string& s)
{
std::string::const_iterator it = s.begin();
while (it != s.end() && std::isdigit(*it)) ++it;
return !s.empty() && it == s.end();
}
int main()
{
int iGumballs;
std::string iUserguessStr;
int iUserguess;
int iGuesses = 0;
while (true)
{
system("CLS");
cin.clear();
iGuesses = 0;
srand(static_cast<unsigned int>(time(0)));
iGumballs = rand()%1000+1;
cout << "How many gumballs are in the bumball jar? You guess! 1-1000" << endl;
do
{
cout << "Enter your guess: ";
cin >> iUserguessStr;
if(is_number(iUserguessStr))
iUserguess = boost::lexical_cast<int>(iUserguessStr); //you can make your own or maybe use lexical cast to transform a string into integer
else
continue; //put some fancy message here warning the user
if(iUserguess > iGumballs)
{
cout << "Too high!" << endl << endl;
}
if(iUserguess < iGumballs)
{
cout << "Too low!" << endl << endl;
}
iGuesses ++;
}
while(iUserguess > iGumballs || iUserguess < iGumballs);
cout << "You guessed the right amout of gumballs" << endl << endl;
cout << "You took " << iGuesses << " guesses" << endl << endl;
system ("pause");
}
return 0;
}
My answer is based on a related problem: How to determine if a string is a number with C++?
Yo can use if(cin) to check the state of the input stream and since operator>> will return the input stream that was passed to it you can use if(cin>>iUserguess)
If cin is in a failed state -maybe because the user entered a non number- the expression if(cin>>iUserguess) will evaluate to false.
If the user enters a non number you will need to call cin.clear() to clear the stream state and cin.ignore() to discard the input, before trying to read a number again.
so using your example, it could be changed to this:
#include <iostream>
#include <ctime>
#include <limits>
using namespace std;
int main()
{
int iGumballs;
int iUserguess;
int iGuesses = 0;
while (true)
{
system("CLS");
iGuesses = 0;
srand(static_cast<unsigned int>(time(0)));
iGumballs = rand()%1000+1;
cout << "How many gumballs are in the bumball jar? You guess! 1-1000" << endl;
do
{
cout << "Enter your guess: ";
if(cin >> iUserguess)
{
iGuesses ++;
if(iUserguess > iGumballs)
{
cout << "Too high!" << endl << endl;
continue;
}
if(iUserguess < iGumballs)
{
cout << "Too low!" << endl << endl;
continue;
}
}
else
{
cout<<"incorrect input - try again\n\n";
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(),'\n');
continue;
}
}
while(iUserguess > iGumballs || iUserguess < iGumballs);
cout << "You guessed the right amout of gumballs" << endl << endl;
cout << "You took " << iGuesses << " guesses" << endl << endl;
system ("pause");
}
return 0;
}
To validate characters you could use the try-catch structure.
-First read in a string and try Typecasting it and handle the errors with try-catch.
-Then use conditions to make sure the input is in range.
-If the input isn't valid, you can write an error message to display.