How do I run part of my code until I break? - c++

I need help with my code I will put it all in if anyone can clean it up so it looks nice but I will then highlight what I need help with.
#include <Windows.h>
#include <stdlib.h>
#include "stdafx.h"
#include <string>
#include <iostream>
#include <ctime>
using namespace std;
int main() {
string ready;
system("#echo off");
system("cls");
cout << "ready to play? (y/n to play.): " << endl;
cin >> ready;
if (ready != "y")
do {
cout << "O.K. Goodbye!" << endl;
return 0;
} while (ready == "y");
cout << "OK!" << endl;
system("pause");
system("cls");
int number = 0;
int min = 1;
int max = 125;
int userinput;
srand(time(0));
number = rand() % (max - min + 1) + min;
int guesses_left = 10;
cout << "please try to guess a number between 1 and 125, you currently have: " << guesses_left << " guesses left" << endl;
cin >> userinput;
if (userinput > number){
cout << "Sorry your guess is too high, please guess again.";
cout << endl;
cout << "you now have: " << guesses_left << " guesses left. Please choose again.";
}
else if (userinput < number){
cout << "Soory, your guess is too low, please guess again." << endl;
cout << "You now have: " << guesses_left << " guesses left. Please choose again.";
}
else if (userinput == number){
cout << "congrats you won :)... Here have a prize as you won with: " << guesses_left << " guesses left." << endl << "no but seriously WELL DONE!!! :D";
system("cd C:\Program Files\Internet Explorer");
system("iexplore https://media.property118.com/wp-content/uploads/2013/12/Best-Property-Forum.jpg");
return 0;
}
return 0; }
The bit I am struggling with is this
cout << "please try to guess a number between 1 and 125, you currently have: " << guesses_left << " guesses left" << endl;
cin >> userinput;
if (userinput > number){
cout << "Sorry your guess is too high, please guess again.";
cout << endl;
cout << "you now have: " << guesses_left << " guesses left. Please choose again.";
}
else if (userinput < number){
cout << "Soory, your guess is too low, please guess again." << endl;
cout << "You now have: " << guesses_left << " guesses left. Please choose again.";
}
else if (userinput == number){
cout << "congrats you won :)... Here have a prize as you won with: " << guesses_left << " guesses left." << endl << "no but seriously WELL DONE!!! :D";
system("cd C:\Program Files\Internet Explorer");
system("iexplore https://media.property118.com/wp-content/uploads/2013/12/Best-Property-Forum.jpg");
return 0;
}
I am trying to loop this segment of code until I am bothered to add in you losing lives in the game. So if I get guess higher it should say it is higher and then loop back to give me another go. I have only started learning C++ yesterday and this is all mostly my code (some of it is adapted from other peoples posts like the srand and number = rand thing are other peoples)

I changed your "y/n" while loop to this :
cout << "ready to play? (y/n to play.): " << endl;
cin >> ready;
if (ready != "y")
{
cout << "O.K. Goodbye!" << endl;
return 0;
}
else
cout << "OK!" << endl;
I am also giving you a while version if you want to force the user to press either 'y' or 'n' to go further :
cout << "ready to play? (y/n to play.): " << endl;
cin >> ready;
while ( ready != 'y' && ready != 'n')
{
cout << "Only answer with 'y' or 'n' "<< endl;
cin >> ready;
}
and the game loop where user guesses to this :
int guesses_left = 10;
cout << "please try to guess a number between 1 and 125, you currently have: " << guesses_left << " guesses left" << endl;
while (guesses_left != 0)
{
cin >> userinput;
if (userinput > number){
cout << "Sorry your guess is too high, please guess again.";
cout << endl;
--guesses_left;
cout << "you now have: " << guesses_left << " guesses left. Please choose again.";
}
else if (userinput < number){
cout << "Soory, your guess is too low, please guess again." << endl;
--guesses_left;
cout << "You now have: " << guesses_left << " guesses left. Please choose again.";
}
else if (userinput == number){
cout << "congrats you won :)... Here have a prize as you won with: " << guesses_left << " guesses left." << endl << "no but seriously WELL DONE!!! :D";
system("cd C:\Program Files\Internet Explorer");
system("iexplore https://media.property118.com/wp-content/uploads/2013/12/Best-Property-Forum.jpg");
return 0;
}
}
cout << "You have used up all your guesses." << endl;
return 0;

Related

C++ Do while loop condition not working

#include<iostream>
#include<ctime>
#include<cstdlib>
using namespace std;
int main(){
int gnumber, rnumber;
char choice;
int tries;
do {
cout << "Welcome to the Number Guessing Game!" << endl;
cout << endl; // breakline
cout << "How many tries: ";
cin >> tries;
cout << endl;
while (tries > 0){
srand(time(NULL));
rnumber = rand() % 99;
cout <<"Enter an integer greater than or equal to 0 and less than 100:";
cin >> gnumber;
system("cls");
if (tries != 1){
if (gnumber < 100 && gnumber >= 0){
if (gnumber == rnumber){
cout << "Congratulations! You've guessed the number." << endl;
tries--;
cout << "Remaining tries: " << tries << endl;
}
else if (gnumber > rnumber){
cout << "Your guess is higher than the number." << endl;
tries--;
cout << " Guess Again!" << endl;
cout << "Remaining tries: " << tries << endl;
}
else{
cout << "Your guess is lower than the number." << endl;
tries--;
cout << " Guess Again!" << endl;
cout << "Remaining tries: " << tries << endl;
}
}
else
cout << "Must greater or equal to 0 and lesser than 100!" << endl;
}
else
{
cout << "Game over!" <<" The number is: " << rnumber << endl;
cout << "Play Again? (Y/N)" << endl;
cin >> choice;
system("cls");
}
}
}while(choice == 'Y' || choice == 'y'); //
system("pause");
return 0;
}
EVEN IF I ENTER CHOICE AS 'N' OR 'n' IT WONT STOP THE LOOP.
And even if I enter 'Y' or 'y', it does not ask how many tries i wanted.
Instead it just asks directly what integer I would want to enter.
Please try to copy and compile the code to further understand what the problem is. Please help.
P.S.: This is a guessing program I'm making by the way...
the bug in your inner loop if the use enters a value other than one in else you don't decrement tries so it gets stuck:
else
{
cout << "Game over!" <<" The number is: " << rnumber << endl;
cout << "Play Again? (Y/N)" << endl;
cin >> choice;
system("cls");
tries--; // add this
}

My program will loop regardless of whatever char I enter

I have been working on a very very basic calculation program in C++. It calculates the square root of a number, and also squares it if the user wants. This is what I have so far (I know it's probably rubbish code, but I'm a beginner just experimenting to see how it all works. Any suggestions greatly appreciated though):
#include <iostream>
#include <stdlib.h>
#include <math.h>
using namespace std;
int number; // Global variables to be used in void functions as well as main.
int squaredNumber;
double sqrtResult;
char input;
char useAgain;
void squareNum(); // Prototypes for the void functions
void sqrtNum();
void useAgainQuery();
int main()
{
retry: // Establishing somewhere to send user if their input is invalid.
system("cls");
cout << "Square Calcualtions" << endl;
cout << "******************" << endl;
cout << endl;
cout << "Do you want to square a number or find the square root of a number?" << endl;
cout << "Please select 1 or 2 respectively." << endl;
cout << endl;
cin >> input;
if (input == '1')
{
cout << "Please press ENTER to continue." << endl;
cin.ignore().get();
squareNum(); // If the input is 1, run the void to square a number.
}
else if (input == '2')
{
cout << "Please press ENTER to continue." << endl;
cin.ignore().get();
sqrtNum(); // If the input is 2, run the void to sqrt a number.
}
else if (input != '1' || '2')
{
system("cls");
cout << "Square Calcualtions" << endl;
cout << "******************" << endl;
cout << endl;
cout << "Your selection was invalid, please enter 1 or 2." << endl;
cin.ignore().get();
goto retry; // If the input isn't either 1 or 2, send back to the start of program.
}
return 0;
}
void squareNum() // function to square the inputted number.
{
system("cls");
cout << "Square Calcualtions" << endl;
cout << "******************" << endl;
cout << endl;
cout << "Enter the number you want to square." << endl;
cin >> number;
cout << "You have chosen: " << number << endl;
cout << "Press ENTER to calculate." << endl;
cin.ignore().get();
system("cls");
squaredNumber = number * number; // Simple maths to find the square number
cout << "You have squared " << number << "." << endl;
cout << "The result was " << squaredNumber << "." << endl;
cout << "Press ENTER to continue." << endl;
cin.get();
useAgainQuery();
return;
}
void sqrtNum()
{
system("cls");
cout << "Square Calcualtions" << endl;
cout << "******************" << endl;
cout << endl;
cout << "Enter the number you would like the square root of." << endl;
cin >> number;
cout << "You have chosen: " << number << "." << endl;
cout << "Press ENTER to calculate." << endl;
cin.ignore().get();
system("cls");
sqrtResult = sqrt(number);
cout << "You have found the square root of " << number << "." << endl;
cout << "The result was: " << sqrtResult << "." << endl;
cout << "Press ENTER to continue." << endl;
cin.get();
useAgainQuery();
return;
}
void useAgainQuery()
{
system("cls");
cout << "Square Calcualtions" << endl;
cout << "******************" << endl;
cout << endl;
cout << "Would you like to make another calculation?" << endl;
cout << "Y for Yes and N for No." << endl;
cout << endl;
cin >> useAgain;
if (useAgain == 'Y' || 'y')
{
retry2: // Establishing somewhere to send user if their input is invalid.
system("cls");
cout << "Square Calcualtions" << endl;
cout << "******************" << endl;
cout << endl;
cout << "Do you want to square a number or find the square root of a number?" << endl;
cout << "Please select 1 or 2 respectively." << endl;
cout << endl;
cin >> input;
if (input == '1')
{
cout << "Please press ENTER to continue." << endl;
cin.ignore().get();
squareNum(); // If the input is 1, run the void to square a number.
}
else if (input == '2')
{
cout << "Please press ENTER to continue." << endl;
cin.ignore().get();
sqrtNum(); // If the input is 2, run the void to sqrt a number.
}
else if (input != '1' || '2')
{
system("cls");
cout << "Square Calcualtions" << endl;
cout << "******************" << endl;
cout << endl;
cout << "Your selection was invalid, please enter 1 or 2." << endl;
cin.ignore().get();
goto retry2;
}
}
else if (useAgain != 'Y' || 'y')
return;
return;
}
So yeah, when I go through and it asks "Would you like to play again", it goes through it over and over. It doesn't matter what key I press but it loops. Any help would be greatly appreciated!
Change your condition here:
if (useAgain == 'Y' || 'y')
to
if (useAgain == 'Y' || useAgain=='y')
Also, change this:
else if (useAgain != 'Y' || 'y')
{
return;
}
to this:
else if (useAgain != 'Y' && useAgain!='y')
{
return;
}
Perhaps try creating a bool variable that controls the entire main loop, like this:
#include <InsertLibrariesHere>
int main(){
bool running=true;
while(running){
//calculations here
//continue(Y/N)?
if (input == N || input == n){running = false;}
}
}
Don't use goto, use a while(1) instead.
your last if statement is wrong, it needs to be
if (input != '1' && input != '2')
You can simplify your comparisons to letters:
if (std::toupper(useAgain) == 'Y')
or
if (std::tolower(useAgain) == 'y')
You can also convert the case after you input:
cin >> useAgain;
useAgain = std::toupper(useAgain);
if (useAgain == 'Y')
There is also std::transform is you need to transform a std::string to all lower or all upper case.

C++ error with input validation in a do-while loop

I'm creating a very simple number guessing game for a school project and am having trouble with the repeating main menu. I created it using a do-while loop and the problem I'm having is that the menu selection variable is an int, and so when I (or the user) enters a non-int input by accident when selecting from the menu the }while(condition) at the end of the main loop can't catch it and the program repeats infinitely. Conversely if you enter an invalid int at menu selection the program catches it displays the "invalid input" message and then repeats the main menu.
It's kind of hard to explain in writing exactly what I mean so here is the source code with relevant lines denoted with an asterisk. I'm saving as .cpp and am compiling in linux using g++ -ansi -pedantic -Wall -Werror The teacher has forbidden hardcoding in conditional statements hence the global constants.
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
const int PLAY = 1, HIGH_SCORE = 2, EXIT = 3;
const char YES = 'y', NO = 'n';
int main()
{
// Randomly generated value
int randomNumber;
// User input
int userGuess, menuChoice;
char repeat;
// Calculated value
int numberOfGuesses;
// Place-holder values (to be replaced by calculated values)
int score1 = 1000, score2 = 2000, score3 = 3000;
cout << endl << endl;
cout << "Greetings! This is a number guessing game where I think of" << endl
<< "a whole number between one and ten and you try to guess it!" << endl
<< "You can guess as many times as you like, so don't be afraid" << endl
<< "to use trial and error, but your score is based on the " << endl
<< "number of guesses you make (the lower the better) so don't " << endl
<< "guess too haphazardly. Remember, only guess whole numbers!" << endl
<< endl;
do
{
cout << endl << "Main menu." << endl
<< "1. Play game" << endl
<< "2. Display high scores" << endl
<< "3. Exit game" << endl
<< "Please select an option: ";
cin >> menuChoice;
if (cin.fail()){
cout << "Please enter a valid choice" << endl;
continue;
}
cin.ignore();
switch(menuChoice)
{
case PLAY:
do
{
unsigned seed = time(0);
srand(seed);
randomNumber = 1 + rand() % 10;
cout << endl << "Press enter when you're ready to begin!";
cin.ignore();
cout << "Ok I thought of one!" << endl << endl;
numberOfGuesses = 0;
do
{
numberOfGuesses++;
cout << "Enter your guess: ";
cin >> userGuess;
cin.ignore();
// Check user's guess
if (userGuess == randomNumber)
cout << "Correct! That was impressive!" << endl << endl;
else if (userGuess < randomNumber)
cout << "Not quite, you guessed low." << endl << endl;
else if (userGuess > randomNumber)
cout << "Not quite, you guessed high." << endl << endl;
}while (userGuess != randomNumber);
cout << "Your score for this game was " << numberOfGuesses << endl;
// Determine if a high score was beaten
if (numberOfGuesses <= score1)
{
score3 = score2;
score2 = score1;
score1 = numberOfGuesses;
cout << "That's a new all time high score!" << endl;
}
else if (numberOfGuesses <= score2)
{
score3 = score2;
score2 = numberOfGuesses;
cout << "That's a new high score!" << endl;
}
else if (numberOfGuesses <= score3)
{
score3 = numberOfGuesses;
cout << "That's a new high score!" << endl;
}
else
{
cout << endl;
}
cout << "Would you like to play again? y/n: ";
cin.get(repeat);
cin.ignore();
while (tolower(repeat) != YES && tolower(repeat) != NO)
{
cout << endl;
cout << "Sorry, that is an invalid choice." << endl
<< "Please enter 'y' for yes or 'n' for no: ";
cin.get(repeat);
cin.ignore();
}
}while (tolower(repeat) == YES);
break;
case HIGH_SCORE:
cout << endl << "High Score 1: " << score1 << endl
<< "High Score 2: " << score2 << endl
<< "High Score 3: " << score3 << endl << endl;
cout << "Press enter to continue. ";
cin.ignore();
break;
case EXIT:
cout << endl << "Thanks for playing, I'll see you next time!" << endl << endl;
break;
default:
cout << endl << "That is an invalid selection, please enter '1', '2' or '3'"
<< endl;
break;
}
}while (menuChoice != EXIT);
return 0;
}
Code Edited in regards to current answer.
Please let me know if you need anymore information, thanks in advanced!
Use cin.fail() like this (instead of just cin >> menuChoice;) (modelled after this post):
cin >> menuChoice;
if (cin.fail()) {
cout << "Please enter a valid choice" << endl;
cin.clear();
cin.ignore();
continue;
}
//Remove the cin.ignore() at this place!
For more detailed info, see this SO thread
Use a do-while to ensure that the loop body will run at least once.
By using a do-while and prompting a user outside the loop you assume the user wants to play the game once which may not be the case.
A cleaner approach IMO would be use a while loop. Display the menu outside the loop and at the end of the loop. The user will have the choice to exit immediately.
cout << "Greetings.....
cout << menu
// Get menuChoice input here.
while(menuChoice != EXIT){
...
cout << menu //reprompt at end to continue or exit cleanly
// Get menuChoice input here
}
Input Validation is a perfect time to use a do-while
do{
if(!cin){
cout << "Invalid input"
cin.clear()
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
}while(!(cin >> menuChoice)) // This gets console input. If fail, loop.
Use numeric_limits<streamsize>::max() to completely clear the
buffer.
Use cin.clear() to reset the fail flag on cin so it wont
always be false.
cin.fail() is fine. However some would consider !cin more natural.

Serendipity booksellers software program C++

this is a project I'm working on which comes from the book I'm using to learn C++ - "Starting out with C++". I'm having a problem with the cashier portion of the project at the moment. It asks the user to enter the date, quantity, isbn, title, and price of the book. Then, it asks the user if they wish to enter another book. Regardless of whether they type "y" or "n" it continues to the next part of the program. I don't really know why the for loop doesn't repeat after I type "y" to enter another book. Also, the date is coming out with garbage at the end when it is displayed, that's another thing I need to fix. Any help would be appreciated. There is definitely more problems but the main problem is in the cashier function in the first for loop. I didn't include the whole program because it's very long.
/*
* mainmenu.cpp
* Serendipity Booksellers software
*
* Created by Abraham Quilca on 9/5/12.
* Copyright 2012 __MyCompanyName__. All rights reserved.
*
*/
#include<iostream>
#include<iomanip>
#include<cstring>
#include"mainmenu.h"
using namespace std;
char bookTitle[20][51],
isbn[20][14],
author[20][31],
publisher[20][31],
dateAdded[20][11];
int qtyOnHand[20];
double wholesale[20];
double retail[20];;
int main()
{
int choice;
do
{
cout << "\t\t Serendipity Booksellers"<< endl;
cout << "\t\t\t Main Menu" << endl << endl;
cout << "\t\t1. Cashier Module" << endl;
cout << "\t\t2. Inventory Database Module" << endl;
cout << "\t\t3. Report Module" << endl;
cout << "\t\t4. Exit" << endl << endl;
cout << "\t\tEnter your choice: ";
cin >> choice;
cout << endl;
switch (choice)
{
case 1:
cashier();
break;
case 2:
invmenu();
break;
case 3:
reports();
break;
case 4:
continue;
break;
default:
cout << "\t\tPlease enter a number in the range 1-4." << endl << endl;
}
}
while(choice != 4);
cout << "\t\tYou selected item 4." << endl;
return 0;
}
// Cashier function
void cashier()
{
char again;
char date[8];
int quantity[20] = {0};
char ISBN[20][20] = {0};
char title[20][40] = {0};
float price[20] = {0}, bookTotal[20] = {0}, subtotal, total, tax;
const float tax_rate = .06;
cout << "Serendipity Booksellers" << endl;
cout << " Cashier Module" << endl << endl;
for(int count = 0; count < 20; count++)
{
cout << "Date: ";
cin >> date;
cout << "Quantity of Book: ";
cin >> quantity[count];
cout << "ISBN: ";
cin >> ISBN[count];
cout << "Title: ";
cin.ignore();
cin.getline(title[count], 40);
cout << "Price: ";
cin >> price[count];
bookTotal[count] = quantity[count] * price[count];
subtotal += price[count];
cout << "Would you like to enter another book? (Y/N) ";
cin >> again;
if(again == 'N' || 'n')
count = 21; // This line will end the for loop
}
// Calculating tax and total
tax = subtotal * tax_rate;
total = subtotal + tax;
cout << "\n\nSerendipity Booksellers" << endl << endl;
cout << "Date:" << date << endl << endl;
cout << "Qty\t ISBN\t\t "
<< left << setw(40) << "Title" << "Price\t Total" << endl
<< "-------------------------------------------------------------------------------"
<< endl << endl;
for(int count = 0; count < 20; count++)
{
cout << quantity[count] << "\t " << ISBN[count] << " " << left << setw(40) << title[count]
<< setprecision(2) << fixed << "$" << setw(6) << price[count] << " $" << setw(6) << bookTotal[count]
<< endl << endl;
}
cout << "\t\t\t Subtotal" << "\t\t\t\t $" << setw(6) << subtotal << endl;
cout << "\t\t\t Tax" << "\t\t\t\t $" << setw(6) << tax<< endl;
cout << "\t\t\t Total" "\t\t\t\t $" << setw(6) << total << endl << endl;
cout << "Thank You for Shopping at Serendipity!" << endl << endl;
}
if(again == 'N' || 'n')
This doesn't do what you think it does. Look at it like this:
if((again == 'N') || ('n'))
Is again == N true OR is n true? Well n will always be true (it is a char with non-zero value) so your loop will always end immediately. What you want is:
if(again == 'N' || again == 'n')
Also, you can break out of a loop using the aptly named break keyword:
if (again == 'N' || again == 'n') {
break;
}
The problem with the loop is this line:
if(again == 'N' || 'n')
C++ doesn't know that you mean it to check again against both characters. Instead, it tries again == 'N', which fails, and then tries 'n', which - not being zero - evaluates as true.
Instead, try:
if (again == 'N' || again == 'n')
break;

Four Errors In C++ Code, I Can't Find The Solutions To

I was looking at some code I'm working on, and there are 3-4 errors that I have tried for about a week to get rid of, and I just can't do it! I'm kind of new to programming, so if you could answer in stupid form, that would be great! Here is the code.
#include <iostream>
#include <string>
using namespace std;
int main() {
string password;
int choice;
cout << "Command Line Multi-Tool" << endl;
cout << endl;
cout << "plase enter your password: " << endl;
cin >> password;
if (password == "creeper1") {
cout << endl;
cout << "Main Menu" << endl;
cout << "1. Class Schedule" << endl;
cout << "2. School Info" << endl;
cout << "3. Exit" << endl;
cin >> choice;
}
else {
cout << "Incorrect, Access Denied" << endl;
return(0);
}
}
else (password == "admin1"){
cout << "/*adminLogin=='1'*/" << endl;
cout << endl;
cout << "Menu::Main" << endl;
}
return(0);
}
}
And here is the error log.
/Users/student/Documents/TO BE FILED/Tuesday/main.cpp:31:0 /Users/student/Documents/TO BE
FILED/Tuesday/main.cpp:31: error: expected unqualified-id before 'else'
/Users/student/Documents/TO BE FILED/Tuesday/main.cpp:36:0 /Users/student/Documents/TO BE
FILED/Tuesday/main.cpp:36: error: expected unqualified-id before 'return'
/Users/student/Documents/TO BE FILED/Tuesday/main.cpp:36:0 /Users/student/Documents/TO BE
FILED/Tuesday/main.cpp:36: error: expected declaration before '}' token
Again thanks so much!
You have one if but 2 else brances in your code. Decide which one you want and lose the other one. Looking at the code you probably want
if (password == "creeper1") {
cout << endl;
cout << "Main Menu" << endl;
cout << "1. Class Schedule" << endl;
cout << "2. School Info" << endl;
cout << "3. Exit" << endl;
cin >> choice;
} else if (password == "admin1")
// Your processing code here
} else {
cout << "Incorrect, Access Denied" << endl;
return(0);
}
Unbalanced else,i.e. without a corresponding if.
Perhaps you wanted something like:
if (password == "creeper1") {
}
else if (password == "admin1") {
}
else {
}
You can't use an else if after an else, that block will never be executed.Also, the right syntax is return 0, not return(0).
You also include extra braces, but if you indent the code in the right way you see when a block ends and starts, so you could rarely make mistakes like adding an extra brace:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string password;
int choice;
cout << "Command Line Multi-Tool" << endl;
cout << endl;
cout << "plase enter your password: " << endl;
cin >> password;
if (password == "creeper1")
{
cout << endl;
cout << "Main Menu" << endl;
cout << "1. Class Schedule" << endl;
cout << "2. School Info" << endl;
cout << "3. Exit" << endl;
cin >> choice;
}
else if(password == "admin1")
{
cout << "/*adminLogin=='1'*/" << endl;
cout << endl;
cout << "Menu::Main" << endl;
}
else
{
cout << "Incorrect, Access Denied" << endl;
return 0;
}
return 0;
}
This is the code with all the syntax errors fixed.About semantics I don't know if it works, but now you can compile and execute it, to test the code.
becasue else cannot comprise judgement
the correct usage is like this:
if(password == "creeper1"){
}
else if(password == "admin1"){
}
else{
}