I think the question speaks for itself, I'm writing a program in c++ and there is a part where the console asks the user which type of input they want to use
while (loop == 5) {
cout << "\nWould you like to enter a depoist or a check? "; //asks for a choice
cin >> choice;
//determines whether or not to close the program
if(choice == 0 || depo == 0 || check == 0) {
return 0;
}//end close if
//choses which type of input to make
if( choice == 1) {
cout << "\nPlease enter check amount: ";
cin >> check;
check += check;
} else if(choice == 2) {
cout << "\nPlease enter deposit amount: ";
cin >> depo;
depo += depo;
}//end if
}
but how do i keep track of how many times the if statement was true?
You can add a counter and increment it every time you enter the if-statement's true block.
int true_counts = 0;
while (loop == 5){
...
if( choice == 1){
true_counts++;
...
Related
I am writing a program, the program is basically a guessing game. Computer displays a number and the user has to guess whether their number is higher, lower or correct. I have already made the program and its all dandy, but the only not dandy part is that I cannot figure out how to get rid of the input buffer when the user decides to play the game again. Every time the user wants to play the game, the game starts again but with the same input as the last game. I have tried putting cin.clear() in any spot I could think and also cin.clear(). But it just seems to not work. How do I clear the input?
#include <iostream>
using namespace std;
int main ()
{
int num1 = 100;
char choice;
num1 = num1 / 2;
do
{
cout << "My guess is " << num1 << ". " << "Enter 'l' if your number is lower, 'h' if it is higher, 'c' if it is correct: ";
cin >> choice;
cin.clear();
if (choice == 'h')
{
num1 = num1 + 100;
num1 = num1 / 2;
}
if (choice == 'l')
{
num1 = num1 + num1;
num1 = num1 - 11;
num1 = num1 / 2;
}
if (choice == 'c')
{
cout << "Great! Do you want to play again (y/n)?: ";
cin >> choice;
}
} while (choice != 'c' || choice == 'Y' || choice == 'y' || choice == 'n' || choice == 'N');
return 0;
}
In order to restart the game, you need to reset num1. Put the inital value in a variable that you don't change.
const int init = 100;
char choice;
int num1 = init / 2;
When the computer has guessed correctly:
if (choice == 'c')
{
num1 = init / 2; // reset
cout << "Great! Do you want to play again (y/n)?: ";
cin >> choice;
}
You could also leave the loop condition at:
} while(choice != 'N' && choice != 'n');
You should also work on the divide and conquer algorithm. For the computer to be effective, it should always make a guess in the middle of the range that is still possible, and that's not what it's doing right now. It jumps up and down, even outside the established range. An alternative could be to keep two variables to be able to shrink the possible range effectively. You could also do two separate loops, one inner loop for guessing the number and one outer that only asks the user if he/she wants to play again.
Example:
#include <iostream>
int main() {
const int initlo = 1;
const int inithi = 100;
char choice;
do {
std::cout << "Think of a number [" << initlo << "," << inithi << "]\n";
int numlo = initlo; // initialize the range
int numhi = inithi;
int guess;
do {
guess = (numlo + numhi) / 2; // guess in the middle of the range
std::cout
<< "My guess is " << guess << ". "
<< "Enter 'l' if your number is lower, 'h' if it is higher, 'c' "
"if it is correct: ";
std::cin >> choice;
if(choice == 'h') // must be in the range (guess,numhi]
numlo = guess + 1;
else if(choice == 'l') // must be in the range [numlo,guess)
numhi = guess - 1;
// exit the loop if the user cheats or the answer is correct
} while(numlo <= numhi && choice != 'c');
if(choice == 'c') std::cout << "Great! ";
else std::cout << "Cheater! ";
std::cout << "Do you want to play again (y/n)?: ";
std::cin >> choice;
} while(choice == 'Y' || choice == 'y');
std::cout << "Bye\n";
}
noob programmer here. Taking my first CS class in college and making first post on here so excuse me if the info i provide is not sufficient in advanced.
Still trying to figure out loops. Seem to get it but once there is loops within loops or if statements inside loops, I get thrown off and have no idea on how to proceed. For my assignment, I need the following to occur.
Would you like to process all the records in the file? (y/n) W
Please enter either y or n.
Would you like to process all the records in the file? (y/n) n
Enter number of records to process: two
XXXXXXXXXX Error-non numeric or negative value, try again
Enter number of records to process: 10
Here is my code:
char a = 0; //User chooses Y or N
int ProcessAmount = 0; //Amount of times to process if not all
cout << "Would you like to process all the records in the file? (y/n) ";
cin >> a;
do{
bool notDone = true;
if(a == 'n'){
while(notDone){
cout << "Enter records to process: ";
cin >> ProcessAmount;
if (cin.fail()){
cin.clear();
cin.ignore(40,'\n');
cout << "" << endl;
}
else{
notDone = false;
}
}
}else if(a != 'y' or a != 'n');
cout <<"Please enter either y or n." << endl;
}while( a != 'y');
Most problems are explained in comments, here is how I would fix it:
char a = 0; //User chooses Y or N
int ProcessAmount = 0; //Amount of times to process if not all
cout << "Would you like to process all the records in the file? (y/n) ";
cin >> a;
while (a != 'y') {
bool notDone = true;
if(a == 'n'){
while(notDone){
cout << "Enter records to process: ";
cin >> ProcessAmount;
if (cin.fail()){
cin.clear();
cin.ignore(40,'\n');
cout << "" << endl;
} else {
notDone = false;
}
}
} else if(a != 'y' or a != 'n') {
cout <<"Please enter either y or n." << endl;
cin >> a; // Need to get new input because old one is invalid.
}
};
Also I don't see how notDone is used. Also I would strongly advise of using proper indentation, spaces around keywords as while, for, if, else as it is good style.
You just put the y/n solicitation out of your loop then 'a' won't never change its value. Take a look of the change you may want:
do {
cout << "Would you like to process all the records in the file? (y/n/f) "; //f to break the loop
cin >> a;
bool notDone = true;
if (a == 'n') {
//. . .
} else if (a == 'y') {
//You may want to do something when yes
} else if (a != 'f')
cout <<"Please enter either y/n or f." << endl;
} while( a != 'f')
need to limit the ammount of items that can be entered into the array to 5. Tought i would use a do while loop but it just continues even after the 5 items have been entered. Any help would be appreciated
#include "stdafx.h"
#include <string>
#include <conio.h>
#include <iostream>
#include <array>
using namespace std;
string sItems[4] = {};
string sChoice = "";
int iItemPrice[4] = {};
int iNumOfItems = 0;
int iMenuChoice = 0;
int iCount = 0;
int main()
{
cout << "--------- Welcome to the program ---------\n\n Please pick from an option below: \n 1: Enter new items \n 2: Change item prices \n 3: Input sold items \n 4: Receipt for previous items sold\n ";
cin >> iMenuChoice;
switch (iMenuChoice)
{
case 1:
{
do {
cout << "--------- ENTER NEW ITEMS ---------\n\nPlease enter the item Name: ";
cin >> sItems[iCount];
cout << "\nPlease enter the price of: " << sItems[iCount] << "\n";
cin >> iItemPrice[iCount];
cout << "\nWould you like to enter another item? Y/N \n";
cin >> sChoice;
if (sChoice == "Y" || sChoice == "y")
{
++iCount;
++iNumOfItems;
}
} while (sChoice == "Y" || sChoice == "y" || iNumOfItems < 5);
cout << "you have entered the maximum ammount of items";
}
}
_getch();
return 0;
}
The loop condition sChoice == "Y" || sChoice == "y" || iNumOfItems < 5 means:
Loop as long as user answers "Y"
But at least 5 times regardless of user answer
If you want some other logic, like loop up to 5 times, then you can reflect that in the code.
Also check for failures. If you input a character when cin expects a number, it will enter a failed state and all subsequent input attempts will fail.
do {
cout << "--------- ENTER NEW ITEMS ---------\n\nPlease enter the item Name: ";
cin >> sItems[iCount];
cout << "\nPlease enter the price of: " << sItems[iCount] << "\n";
if (!(cin >> iItemPrice[iCount]))
break;
cout << "\nWould you like to enter another item? Y/N \n";
cin >> sChoice;
++iCount;
++iNumOfItems;
} while ((sChoice == "Y" || sChoice == "y") && iNumOfItems < 5);
And increase the array size from 4 to 5 if you want to support 5 items:
string sItems[5];
int iItemPrice[5];
when user inputs 'y' or 'Y' for "Do you wish to enter another year? (Y/N): ", loops "the month has 0 days" forever. Why?
I tried to look at the values and it seems like the values stored are being used again. Maybe I am not using cin.clear() correctly?
//variables
bool ucontinue = true; //answer to continue
int year = 0;
int month = 0;
int days = 0;
char answer = 'a';
//loop
while (ucontinue == true)
{
/*
Enter a year (Must be a positive integer): 2016
Enter a month (Must be a between 1 and 12): 2
The month has 29 days.
Do you wish to enter another year? (Y/N): y
*/
//year input
while (year <= 0)
{
cout << "Enter a year (Must be a positive integer): ";
cin >> year;
}
//month input
while (month <= 0)
{
cout << "Enter a month (Must be a between 1 and 12):";
cin >> month;
}
//# of days in the month
cout << "The month has " << days << " days." << endl << endl;
//continue?
while (answer != toupper('y') && answer != toupper('n'))
{
cout << "Do you wish to enter another year? (Y/N): ";
cin >> answer;
answer = toupper(answer);
if (answer == toupper('n'))
{
ucontinue = false;
}
}
cin.clear();
}
you code loops forever because of you while loops the the first time you run the program it works fine but the second time it goes around all the values are set for example the second time you go through the loop this while statement
while (year <= 0)
{
cout << "Enter a year (Must be a positive integer): ";
cin >> year;
}
won't run because year is already greater than 0 and this happens for all the while statements in your code. what would work is if you have do while statements instead of while statements because do while statements will run through the loop once before testing the condition it. like this:
do
{
cout << "Do you wish to enter another year? (Y/N): ";
cin >> answer;
answer = toupper(answer);
if (answer == toupper('n'))
{
ucontinue = false;
}
}while(answer != 'Y' && answer != 'N');
If I understand correctly you do the following:
Enter a year (Must be a positive integer): 2017
Enter a month (Must be a between 1 and 12):5
The month has 0 days.
Do you wish to enter another year? (Y/N): y <ENTER>
and your program loops. What happens it the following:
cin.clear();
is executed and your loop starts again. At this point year and month are still set. So when in the new loop iteration the line
while (year <= 0)
is encountered the condition is false and the loop continues to
while (month <= 0)
for this line the same is true. After that
cout << "The month has " << days << " days." << endl << endl;
is printed and the condition in
while (answer != toupper('y') && answer != toupper('n'))
is checked. As I have just entered y this condition is not true and
cin.clear();
is executed next, after this the loop restarts ad infinitum.
Your programs have many problems
you never updated or input something on the days variable so it will always be 0 as you set it in the beginning of the program
if (answer == toupper('n')) can be reduced to if (answer=='N')
I need to do a Guessing game where the program generates a random number and the user has to guess the number. If the user guesses the number in less than 10 guesses the program congratulates them and lets them know they were under 10 guesses. If they were above 10 guesses then it lets them know it was above 10, etc.
The problem I'm facing is if, for example, the user guesses the number in 3 tries and then decides to play again with a whole new other number, and this time guesses it in 8 tries, instead of still congratulating them because it was under 10 tries, it counts the 3 tries from the previous game. This then leads the program to tell them they were over 10 tries, even though they were not. I don't know how to fix this. The code I've done so far is as follows:
int main()
{
srand(time(0));
int guess;
int number;
char selection = 'y';
int numberOfGuesses=0;
while(selection == 'y' || selection == 'Y')
{
number = rand() % 1000 + 1;
cout << "I have a number between 1 and 1000.\nCan you guess my number?\nPlease type your first guess: ";
cin >>guess;
do
{
if(number > guess)
{
cout << "Too low. Try again: " << endl;
cin >> guess;
numberOfGuesses++;
}
if (number < guess)
{
cout << "Too high. Try again: " << endl;
cin >> guess;
numberOfGuesses++;
}
}
while(number != guess);
if(numberOfGuesses < 9)
{
cout << "You guessed the number in less than 10 guesses!\n Would you like to play again (y or n)?";
cin >> selection;
}
else if(numberOfGuesses > 9)
{
cout << "You guessed the number\n Would you like to play again (y or n)?";
cin >> selection;
}
else if(numberOfGuesses == 9)
{
cout << "You guessed the number.\n Would you like to play again (y or n)?";
cin >> selection;
}
}
return 0;
}
The problem is that you are not resetting the counter.
Just put int numberOfGuesses=0; within the while loop:
while(selection == 'y' || selection == 'Y')
{
int numberOfGuesses=0;
....
}
You need to set numberOfGuesses to 0 before every game. Your program only sets it once when the program first launched.
You are not resetting numberOfGuesses to zero after each round. You can solve the problem using one of couple of methods.
Reset the value of numberOfGuesses to zero at the end of the first while loop.
while(selection == 'y' || selection == 'Y')
{
...
numberOfGuesses = 0;
}
Don't define the variable until the start of that while loop. Define it as the first statement and initialize it zero.
while(selection == 'y' || selection == 'Y')
{
int numberOfGuesses = 0;
...
}