Validation While Loop Only Repeating Every Other Time - c++

I'm creating a program that is an arithmetic quiz. The program displays a menu and presents a quiz depending on the option that the user chooses (1 for addition, 2 for subtraction, etc.).
My while loops that validate if the user answered a problem correctly or incorrectly seems to be repeating every other time as opposed to every time. This ends up affecting the correct/incorrect counters for how many questions a user answers correctly/incorrectly, and I haven't been able to figure out why this is happening - what do I need to fix?
I am also having issues where the loop doesn't end even if the user enters -1 to stop.
#include <cstdlib>
#include <ctime>
using namespace std;
// function prototypes
void showMenu();
int add(int, int);
// main function
int main()
{
int choice = 0, answer = 0; // user input
int num1, num2; // numbers for problem
int correct_sum; // correct answer
int correct = 0, incorrect = 0; // counters
do
{
// display program purpose to user
cout << "********* Welcome to the Arithmetic Quiz *******\n";
cout << '\n';
// call showMenu function
showMenu();
cin >> choice; // user inputs menu choice
cout << '\n';
// switch statement for menu choice
switch (choice)
{
// addition
case 1:
do {
// randomize numbers
srand(time(NULL)); // random seed
num1 = rand() % 9 + 1; // random num1
num2 = rand() % 9 + 1; // random num2
// display problem to user
cout << "How much is " << num1 << " plus " << num2 << "?\n";
cout << "Enter your answer (-1 to return to the menu)\n";
cin >> answer;
cout << '\n';
// correct sum formula & call addition() function
correct_sum = add(num1, num2);
// while user's answer is WRONG and not -1
while (answer != correct_sum && answer != -1)
{
// display incorrect message
cout << "No. Please try again.\n";
incorrect++; // increment incorrect counter
// ask user for input again
cout << "Enter your answer (-1 to return to the menu)\n";
cin >> answer;
cout << '\n';
}
// while user's answer is RIGHT
while (answer == correct_sum)
{
// display correct message
cout << "Very Good!\n";
correct++; // increment correct counter
// randomize numbers again for different problem
srand(time(NULL)); // random seed
num1 = rand() % 9 + 1; // random num1
num2 = rand() % 9 + 1; // random num2
// show more problems to user until -1 is entered
cout << "How much is " << num1 << " plus " << num2 << "?\n";
cout << "Enter your answer (-1 to return to the menu)\n";
cin >> answer;
cout << '\n';
}
} while (answer != -1);
if (answer == -1)
{
// display addition results when answer == STOP
cout << "********* RESULTS *******\n";
cout << '\n';
cout << "Addition problems solved: " << (correct + incorrect) << '\n';
cout << "Number answered correctly: " << correct << '\n';
cout << "Number answered incorrectly: " << incorrect << '\n';
}
}
// --------------------------------------------------------------------------------------
// showMenu function
void showMenu()
{
// display menu options
cout << "MENU:\n";
cout << '\n';
cout << "1. Enter 1 for Addition\n";
cout << "2. Enter 2 for Subtraction\n";
cout << "3. Enter 3 for Multiplication\n";
cout << "4. Enter 4 for Division\n";
cout << "5. Enter 5 for Modulus\n";
cout << "6. Enter 6 to Exit\n";
cout << '\n';
}
// --------------------------------------------------------------------------------------
// add function
int add(int num1, int num2)
{
return (num1 + num2);
}

You don't have yo use while loop inside do..while loop, if condition will work there, Try below code i have commented some part of code.
#include<iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
// function prototypes
void showMenu();
int add(int, int);
// showMenu function
void showMenu()
{
// display menu options
cout << "MENU:\n";
cout << '\n';
cout << "1. Enter 1 for Addition\n";
cout << "2. Enter 2 for Subtraction\n";
cout << "3. Enter 3 for Multiplication\n";
cout << "4. Enter 4 for Division\n";
cout << "5. Enter 5 for Modulus\n";
cout << "6. Enter 6 to Exit\n";
cout << '\n';
}
// --------------------------------------------------------------------------------------
// add function
int add(int num1, int num2)
{
return (num1 + num2);
}
// main function
int main()
{
int choice = 0, answer = 0; // user input
int num1, num2; // numbers for problem
int correct_sum; // correct answer
int correct = 0, incorrect = 0; // counters
do
{
// display program purpose to user
cout << "********* Welcome to the Arithmetic Quiz *******\n";
cout << '\n';
// call showMenu function
showMenu();
cin >> choice; // user inputs menu choice
cout << '\n';
// switch statement for menu choice
switch (choice)
{
// addition
case 1:
do {
// randomize numbers
// srand(time(NULL)); // random seed
num1 = rand() % 9 + 1; // random num1
num2 = rand() % 9 + 1; // random num2
// display problem to user
cout << "How much is " << num1 << " plus " << num2 << "?\n";
cout << "Enter your answer (-1 to return to the menu)\n";
cin >> answer;
cout << '\n';
// correct sum formula & call addition() function
correct_sum = add(num1, num2);
// while user's answer is WRONG and not -1
while(answer != correct_sum && answer != -1)
{
// display incorrect message
cout << "No. Please try again.\n";
incorrect++; // increment incorrect counter
// ask user for input again
cout << "Enter your answer (-1 to return to the menu)\n";
cin >> answer;
correct_sum = add(num1, num2);
cout << '\n';
}
// while user's answer is RIGHT
if (answer == correct_sum)
{
// display correct message
cout << "Very Good!\n";
correct++; // increment correct counter
// randomize numbers again for different problem
// srand(time(NULL)); // random seed
num1 = rand() % 9 + 1; // random num1
num2 = rand() % 9 + 1; // random num2
// show more problems to user until -1 is entered
//cout << "How much is " << num1 << " plus " << num2 << "?\n";
//cout << "Enter your answer (-1 to return to the menu)\n";
//cin >> answer;
cout << '\n';
}
} while (answer != -1);
if (answer == -1)
{
// display addition results when answer == STOP
cout << "********* RESULTS *******\n";
cout << '\n';
cout << "Addition problems solved: " << (correct + incorrect) << '\n';
cout << "Number answered correctly: " << correct << '\n';
cout << "Number answered incorrectly: " << incorrect << '\n';
}
}
}while (answer != -1);
}
// --------------------------------------------------------------------------------------
Output of above code now if answer is not correct
********* Welcome to the Arithmetic Quiz *******
MENU:
1. Enter 1 for Addition
2. Enter 2 for Subtraction
3. Enter 3 for Multiplication
4. Enter 4 for Division
5. Enter 5 for Modulus
6. Enter 6 to Exit
1
How much is 6 plus 9?
Enter your answer (-1 to return to the menu)
10
No. Please try again.
Enter your answer (-1 to return to the menu)
10
No. Please try again.
Enter your answer (-1 to return to the menu)
10
No. Please try again.
Enter your answer (-1 to return to the menu)
10
No. Please try again.
Enter your answer (-1 to return to the menu)
10
No. Please try again.
Enter your answer (-1 to return to the menu)
10
No. Please try again.
Enter your answer (-1 to return to the menu)
10
I hope you are expecting this.

Related

testing an isbn number to see if its valid

I am having trouble with a homework assignment where I need to check if the ISBN code is valid. This is a beginner C++ class, and I am new to all of this. Right now, no matter what ISBN I put in, it tells me they are all valid. If someone could help point me in the right direction to figure out if my formula is correct when in my for() statement.
I have no problem with the outside loops, it's just the conversion I believe I am doing wrong.
being this is an intro c++ class, we are still only using basic functions, so the professor suggested reading in the ISBN and storing it under a char variable.
**#include <iostream>
using namespace std;
int main()*
{
int Counter;
int WeightedSum;
char ISBN[11] = { 0 };
char Choice;
char Again{};
int Sum = 0;
const char X = 10;
int IterationCounter = 0;
do // begininng of do/while loop
{
cout << "Would you like to check if your ISBN is valid or not? ";
cout << "Press Y/y for yes or N/n for no and to end program: ";
cin >> Choice; //choice input
cout << endl << endl; // blank line
while (Choice != 'Y' && Choice != 'y' && Choice != 'N' && Choice != 'n') // beginning of while loop. checks user input to see if valid y/n choice
{
cout << "Invalid choice! Enter either Y/y or N/n"; // displays when anything other than y/n is entered
cout << "Press Y/y for yes or N/n for no and to end program: "; //gives user another chance to enter y/n
cin >> Choice;
cout << endl << endl;
}
if (Choice == 'Y' || Choice == 'y')
{
cout << "Enter the ISBN you wish to convert: " << endl;
cin >> ISBN;
cout << ISBN;
cout << endl << endl;
for (Counter = 0; Counter < 10; Counter++)
{
WeightedSum = ISBN[10] * (10 - Counter);
Sum = WeightedSum + Sum;
}
cout << Sum;
if (Sum % 11 == 0)
{
cout << Sum;
cout << " Is a valid ISBN " << endl;
}
else
{
cout << Sum;
cout << " Is invalid " << endl;
}*
The problem is this line
WeightedSum = ISBN[10] * (10 - Counter);
You're always performing math against the character at position 11. Because you multiply it by 10 - Counter, which is 0 through 9, you're going to basically be multiplying it by the sum of 1 through 10, or 55. Since 55 is divisible by 11, you'll always end up with if (Sum % 11 == 0) evaluating to true. Worst case, you may even hit an access violation since you're not checking the length of ISBN before accessing it.

Guess the random number game

I am making a number guessing game and I do not know how to incorporate a certain number of guesses the users has to get the correct answer. I want the user to have only 3 guesses to guess the number but after 3 guesses, they lose if they do NOT get it correct. Here is my code below:
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
srand ( time(NULL) );
cout << "Select a difficulty: 1) Easy, 2) Medium, 3) Hard " << endl;
int userlevel;
int userinput;
int randomNumber;
cin >> userlevel;
{
if (userlevel==1)
cout << "You chose Easy: 3 chances to guess correctly" << endl;
cout << "Pick a number between 1 and 10: " << endl;
cin >> userinput;
randomNumber = rand() % 10 + 1;
if (randomNumber==userinput)
cout << "You, guessed correctly! You win!" << endl;
else
cout << "I'm sorry, that is not correct. You lose." << endl;
}
{
if (userlevel==2)
cout << "You chose Medium: 4 chanaces to guess correctly" << endl;
cout << "Pick a number between 1 and 50: " << endl;
cin >> userinput;
randomNumber = rand() % 50 + 1;
if (randomNumber==userinput)
cout << "You, guessed correctly! You win!" << endl;
else
cout << "I'm sorry, that is not correct. You lose." << endl;
}
{
if (userlevel==3)
cout << "You chose Hard: 5 chances to guess correctly" << endl;
cout << "Pick a number between 1 and 100: " << endl;
cin >> userinput;
randomNumber = rand() % 100 + 1;
if (randomNumber==userinput)
cout << "You, guessed correctly! You win!" << endl;
else
cout << "I'm sorry, that is not correct. You lose." << endl;
}
return 0;
}
You should look into while-loops. It would be used like this:
int main() {
//...everything above this in yours is good
int Number_to_guess = (rand() % 10 + 1);
int NChances = userlevel + 2;
cout << "You have " << NChances << " chances to guess right.\n";
while (NChances != 0)
{
cout << "Guess: ";
cin >> userinput;
if (userinput == Number_to_Guess) {
cout << "You win! Congrats!\n";
break; // this will break out of the while-loop
}
NChances--; // this will count down the chances left
}
if (NChances == 0) {
cout << "Sorry, you lose. Try again next time!\n";
}
return 0;
}
The main think you're missing here is a loop around the guess limit. So after you figure out what level they are, you can say something like the following pseudocode:
While (counter <= 3)
*Your If Statements*
counter = counter +1
Make sure that in the if statement where they guessed the number right, you break them out of the loop early.
Finally, it might make more sense to guess a number before you enter the loop. So, something like they pick the difficulty, the random number is picked depending on what they say, and then the loop begins. The way it is now, a new random number will be created each time through the loop. I'm not sure if that's intended.

how do you do a integer validation in C++?

ok, I have been looking for days now but I cant find anything that will work.
I have a program and I want to make sure that the user enters a integer and not a double.
this program works fine but I need to validate the numOne and numTwo to make sure they are integers and not doubles, (5.5)
int main()
{ //This is where my variables are stored
int numOne, numTwo, answer, rightAnswer, ranNumOne, ranNumTwo;
//this will display to the user to enter a range of numbers to be used
cout << "Please enter a set of numbers to be the range for the problems." << endl;
cout << "Please enter the beginning number." << endl;
cin >> numOne;
cout << "please enter the ending number." << endl;
cin >> numTwo;
//this makes sure that the user entered a integer(if not the program will close)
if (!(cin >> numOne))
{
cout << "You did not enter a integer PLEASE RE-RUN THE PROGRAM AND TRY AGAIN!" << endl;
cin.clear();
cin.ignore(100, '\n');
exit(0);
}
cout << "please enter the ending number." << endl;
cin >> numTwo;
//this makes sure that the user entered a number(if not the program will close)
if (!(cin >> numTwo))
{
cout << "You did not enter a integer PLEASE RE-RUN THE PROGRAM AND TRY AGAIN!" << endl;
cin.clear();
cin.ignore(100, '\n');
exit(0);
}
//this is where the first number is generated
srand(time(0));
ranNumOne = rand() % (numOne - numTwo) + 1;
system("PAUSE");
//this is where the second number is generated
srand(time(0));
ranNumTwo = rand() % (numOne - numTwo) + 1;
//this is where the calculations are done
rightAnswer = ranNumOne + ranNumTwo;
//this displays the problem that was generated
cout << "What is: " << endl;
cout << setw(11) << ranNumOne << endl;
cout << setw(6) << "+" << setw(3) << ranNumTwo << endl;
cout << " -------\n";
cin >> answer;
//this checks to see if the answer is right or not and displays the result
if (answer == rightAnswer)
{
cout << "Your answer was correct! " << endl;
}
else
cout << "The correct answer is: " << rightAnswer << endl;
return 0;
}
Use std:n:ci.fail() to see if it failed.
int numOne;
cin >> numOne;
if(cin.fail())
cout << "Not a number...")
Maybe even a nice template function.
template<typename T>
T inline input(const std::string &errmsg = "") {
T var;
std::cin >> var;
while (std::cin.fail()) {
std::cin.clear();
std::cin.ignore(256, '\n');
std::cout << errmsg;
std::cin >> var;
}
return var;
}
Or not:
#include <iostream>
#include <cstdlib>
#include <iomanip>
#include <string>
#include <ctime>
#define DIFF(n1, n2) (n1 > n2 ? n1 - n2 : n2 - n1)
using namespace std;
int input(const string &firstmsg = "", const string &errmsg = "") {
int var;
std::cout << firstmsg;
std::cin >> var;
while (cin.fail()) {
cin.clear();
cin.ignore(256, '\n');
cout << errmsg;
cin >> var;
}
return var;
}
int main(){
//This is where my variables are stored
int numOne, numTwo, answer, rightAnswer, ranNumOne, ranNumTwo;
//this will display to the user to enter a range of numbers to be used
cout << "Please enter a set of numbers to be the range for the problems." << endl << endl;
numOne = input("Please enter the beginning number: ", "Invalid. Enter again: ");
//this asks the user for the second number
numTwo = input("Please enter the ending number: ", "Invalid. Enter again: ");
//this is where the first number is generated
srand(time(0));
ranNumOne = rand() % (DIFF(numOne, numTwo)) + 1; // ensures it will always be positive
system("PAUSE");
//this is where the second number is generated
srand(time(0));
ranNumTwo = rand() % (DIFF(numOne, numTwo)) + 1;
//this is where the calculations are done
rightAnswer = ranNumOne + ranNumTwo;
//this displays the problem that was generated
cout << "What is: " << endl;
cout << setw(11) << ranNumOne << endl;
cout << setw(6) << "+" << setw(3) << ranNumTwo << endl;
cout << " -------\n";
cin >> answer;
//this checks to see if the answer is right or not and displays the result
if (answer == rightAnswer){
cout << "Your answer was correct! " << endl;
}
else
cout << "The correct answer is: " << rightAnswer << endl;
return 0;
}
why not, get the number into a double and then see if that double is an int. ie
double d;
cin>>d;
if (ceil(d) != d)
cout >> " not an integer";

Why does one of my 'while' statements execute when another one of my 'while' statements is true?

Note: I am using C++
Why does one of my 'while' statements ('while' number 1) execute anyway when another one of my 'while' statements ('while' number 2) placed above it is valid? This bothers me, because though 'while' number 1 is not true, but 'while' number 2 is true, 'while' number 1 executes anyway instead of 'while' number 2. Can anyone help me, or explain this? Here is my code:
#include <iostream>
#include <string>
using namespace std;
void PancakeGlutton()
{
int answer;
cout << "Good morning!" << endl;
cout << "Would you like to enter pancake data? Press 1 to accept, press 2 to decline: ";
cin >> answer;
while (answer == 1) {
int totalPeople = 10;
int totalPancakes = 0;
int input;
int lowest = 100000;
int highest = 0;
for (int i = 9; i >= 0; --i) {
cout << "How many pancakes did you eat this morning? I will be asking this question " << i << " more times." << endl;
cin >> input;
totalPancakes += input;
if (input >= highest) {
highest = input;
}
if (input <= lowest) {
lowest = input;
}
}
double pancakeAverage = double(totalPancakes) / double(totalPeople);
cout << "The total number of pancakes eaten was " << totalPancakes << " pancakes " << endl;
cout << "The average number of pancakes eaten was " << pancakeAverage << " pancakes " << endl;
cout << "The highest number of pancakes eaten was " << highest << " pancakes" << endl;
cout << "The lowest number of pancakes eaten was " << lowest << " pancakes" << endl;
cout << "" << endl;
cout << "Do you want to enter more pancake data? Press 1 to accept, press 2 to decline: ";
cin >> answer;
}
// while number 1:
while (answer == 2) {
break;
}
// while number 2:
while (answer != 1 || answer != 2) {
cout << "Error: please enter a valid answer. 1 or 2? ";
cin >> answer;
}
}
int main()
{
PancakeGlutton();
system("PAUSE");
return EXIT_SUCCESS;
}
while (answer != 1 || answer != 2) {
cout << "Error: please enter a valid answer. 1 or 2? ";
cin >> answer;
}
must be
while (answer != 1 && answer != 2) {
cout << "Error: please enter a valid answer. 1 or 2? ";
cin >> answer;
}

Multiplying two integers if initial input is an odd integer in C++

I'm working on a homework assignment for a beginning C++ class and I'm a bit lost.
Here's the assignment:
Create a c++ program which ask the user to input a number.
The output of the program should be one of the following:
You entered an EVEN number.
OR
You entered an ODD number.
if the user entered an ODD number, ask them to enter another number.
Multiply this number by the first number and output the result.
The even/odd part is pretty easy- I got that part to work. I've gotten completely lost on the second part. I'm getting so many lines of errors I can't even figure out where the beginning is. If anyone could give me a hint as to what I'm doing wrong, I'd greatly appreciate it.
#include <iostream>
using namespace std;
int main () {
int num1; // This is the original number entered by the user.
int num2; // This is the second number entered if the first number is odd.
cout << "Enter a number: "<< endl;
cin >> num1 >> endl;
if (num1 % 2 == 0) {
cout << num << " Your number is even." << endl;
} if (num1 % 2 != 0) {
cout << num1 << " Your number is odd. Please enter another number: “<< endl;
cin >> num1 >> endl;
} // end of if odd
cout << " Your two numbers multiplied equals (num1 *= num2)” << endl;
} // end of main ()
#include <iostream>
using namespace std;
int main () {
int num1; // This is the original number entered by the user.
int num2; // This is the second number entered if the first number is odd.
cout << "Enter a number: "<< endl;
cin >> num1;
if (num1 % 2 == 0) {
cout << num1 << " Your number is even." << endl;
}
else {
cout << num1 << " Your number is odd. Please enter another number: " << endl;
cin >> num2;
cout << " Your two numbers multiplied equals " << num1*num2 << endl;
} // end of if odd
return 0;
} // end of main ()
Here's fixed code. You tried to cout << num, but there's no num variable, should be num1, also it's wrong to cin >> endl.
What was unexpected, your ” at the end is not a " but something else and it produces a lot of errors.
The part for the odd values
if (num1 % 2 != 0) {
cout << num1 << " Your number is odd. Please enter another number: “<< endl;
cin >> num2 >> endl;
cout << " Your two numbers multiplied equals:" << (num1 * num2) << endl;
}
after corrections
if (num1 % 2 != 0) {
cout << num1 << " Your number is odd. Please enter another number:"<< endl;
cin >> num2;
cout << " Your two numbers multiplied equals:" << (num1 * num2) << endl;
}
do not place formulas between quotaion marks. this turns them into strings or chars that cant be executed as desire. ie cout << " Your two numbers multiplied equals (num1 *= num2)” << endl;
placing the statement cout << " Your two numbers multiplied equals (num1 *= num2)” << endl; out side the if statement causes the statement to be run even if the number was not odd. this doesnt comply with the assignment. and num2 being null still will cause an error