testing an isbn number to see if its valid - c++

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.

Related

C++ Error: Continue option is not working and is looping the program instead

Note: I am a beginner in C++, so please bear with me if there are any serious programming errors that can be fixed easily.
Edit: Options 3 and 4 work perfectly fine without any errors. However, Option 2 has a serious looping problem where 'Error! Number should be in range of (1 to 100)' and 'Enter the number again:' loop continuously when you input any key. Will change the code to show the code for Option 2 and remove Option 3 and Option 4's code.
I created a math program that can calculate numbers, calculate fractions, among other features I added. I added a continue button on some programs (Option 2) that when you enter 'Y' on your keyboard, it should loop the program until the user types a different key to signify that the program should stop. However, the continue button seems not to work. When I press any other key, the program still loops and I have to stop the program so it cannot loop.
#include <<iostream>>
#include <<cmath>>
using namespace std;
int main()
{
std::cout << "Math Application Version 0.1 (currently in development)\n";
std::cout << "Choose an application to use (use numbers 1 - 10)\n":
std::cout << "Option 1: Calculator" << std::endl "Option 2: Use Average Calculator" <<
std::endl << "Option 3: Use Fraction Calculator\n" << std::endl <<
"Option 4: Use LCM (Lowest Common Denominator) Calculator\n";
int choice;
std::cin >> choice;
switch (choice)
{
case 1:
// this is blank on purpose because this would get too long if I added more features here
case 2:
{
printf("\n Chose average calculator.");
char d;
int n, i;
float num[100],
sum=0.0,
average;
anon:
{
cout << "Enter the numbers of data (limit is 100) : ";
cin >> n;
while (n > 100 || n <= 0)
{
cout << "Error! Number should be in range of (1 to 100)." << endl;
cout << "Enter the number again: ";
cin >> n;
}
for (i = 0; i < n; ++i)
{
cout << i + 1 << ". Enter number: ";
cin >> num[i];
sum += num[i];
}
average = sum / n;
cout << "Average = " << average;
}
cout << "\nDo you want to continue? "; cin >> n;
if (n== 'Y', "Yes")
goto anon;
system("PAUSE");
return 0;
break;
}
I'd appreciate any help on this issue or a detailed explanation since this is very confusing for me.
Your code is fine but you just have some typos in these lines.
cout << "\nDo you want to continue? ";
cin >> n;
/*Here => */ if (n== 'Y', "Yes")
fix it to if(n == 'Y'), also you have unintentionally used n instead of the char d that you have defined to use as a check.
So your code should be
cout << "\nDo you want to continue? ";
cin >> d;
if (d == 'Y') { .... }
And for completion, avoid goto whenever you can. You can use a while loop instead of the assembly-like goto.
This is your code but with a while loop instead of goto
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
std::cout << "Math Application Version 0.1 (currently in development)\n";
std::cout << "Choose an application to use (use numbers 1 - 10)\n";
std::cout << "Option 1: Calculator" << std::endl << "Option 2: Use Average Calculator" <<
std::endl << "Option 3: Use Fraction Calculator\n" << std::endl <<
"Option 4: Use LCM (Lowest Common Denominator) Calculator\n";
int choice;
std::cin >> choice;
switch (choice)
{
case 1:
// this is blank on purpose because this would get too long if I added more features here
case 2:
printf("\n Chose average calculator.");
char d = 'Y';
int n, i;
float num[100],
sum=0.0,
average;
while (d == 'Y'){
cout << "Enter the numbers of data (limit is 100) : ";
cin >> n;
while (n > 100 || n <= 0)
{
cout << "Error! Number should be in range of (1 to 100)." << endl;
cout << "Enter the number again: ";
cin >> n;
}
for (i = 0; i < n; ++i)
{
cout << i + 1 << ". Enter number: ";
cin >> num[i];
sum += num[i];
}
average = sum / n;
cout << "Average = " << average;
cout << "\nDo you want to continue? ";
cin >> d;
}
break;
}
}

Validation While Loop Only Repeating Every Other Time

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.

How do I validate user input with c++?

Hey so this is really getting on my nerves.
I'm trying to validate user input within a loop.
I need the user input to be between 0 and 60. I can validate it no problem but what I want it to do is re-ask the previous question if the input is incorrect, you know? like repeat the loop if that makes sense
int main()
{
//Constants
const int MAXROUNDS = 4;
const int NUMARCHERS = 3;
//Variables
int archerNum;
int roundNum;
double score;
double total;
//Start of outer loop, this loop displays each Archer
for (archerNum = 1; archerNum <= NUMARCHERS; archerNum++)
{
total = 0; //This clears the total for the archer
//Start of second loop, this loop displays each round
for (roundNum = 1; roundNum <= MAXROUNDS; roundNum++)
{
cout << "Enter Round " << roundNum << " score for Archer "
<< archerNum << ": ";
cin >> score;
if (score < 0 | score > 60)
{
cout << "ERROR! Number must be between 0 and 60!";
}
}
total = score + score + score + score; //This calculates the total score for the tournament
cout << "\nThe total score for archer " << archerNum << " is: "
<< total << "\n\n";
}
return 0;
}
This is my code ^
Now I have tried so many things. I've looked through my textbook and I've googled everything but I cant seem to find the answer.
I've tried putting the error message in a do-while loop
i've used if-else statements
i've used while loops
I think I've literally used every different type of loop there is and I still cant seem to figure it out and I'm becoming very frustrated.
Thanks in advance
Here is a simple version of just the number input and error message:
//#include "pch.h" if using Visual Studio 2017
#include <iostream>
using namespace std;
int main(){
cout << "Please enter a number between 0 and 60." << endl;
int input;
cin >> input;
while(input < 0 || input > 60 || cin.fail()){ //Using cin.fail() here in case the user enters a letter or word
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cerr << "Number must be between 0 and 60. Please try again." << endl;
cin >> input;
}
return 0;
}`
Alternatively, you could use a goto statement though, as I am sure many others on this site will tell you, that is not recommended as it leads to the infamous 'spaghetti code'.
Simply add roundNum -= 1; inside the validation If statement. It will make the counter decreased by 1, and re-ask the previous question
//Start of second loop, this loop displays each round
for (roundNum = 1; roundNum <= MAXROUNDS; roundNum++)
{
std::cout << "Enter Round " << roundNum << " score for Archer "
<< archerNum << ": ";
std::cin >> score;
if (score < 0 || score > 60)
{
std::cout << "ERROR! Number must be between 0 and 60!"<<endl;
roundNum -= 1; //or roundNum--
}
}
Try:
bool inputError;
do {
inputError = false;
std::out << "Enter Round "
<< roundNum
<< " score for Archer "
<< archerNum << ": ";
if (std::cin >> score) {
if (score < 0 || score > 60)
{
std::cout << "ERROR! Number must be between 0 and 60!";
inputError = true;
}
}
else {
std::cout << "ERROR! Your input must be a number";
inputError = true;
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max());
}
} while(inputError == true);

How to successfully restart loop and accept new responses?

I am attempting to create a program that can print ascii art letters when given J, E, or C and the size (7 or greater and an odd number). I have been able to successfully run the program until I added a Y/N response prompt. I would like to ask the user if they would like to continue, if yes, then I would like to restart the loop. However, I'm trying to write the code to meet the conditions of if they enter 'e' then 'e' ascii art prints, if they enter 'c' then ascii art prints, etc. However, I cannot figure out how to restart the loop and accept new information.
Also, my current predicament is that the do loop is not meeting with my last while loop for a 'No' response. I'm new to C++ and would appreciate any help that can be provided. Thank you!
#include <iostream>
using namespace std;
int main() {
int s;
char l;
char choice;
cout << "Welcome to the letter printer." << endl;
do {
cout << "Enter the size: " << endl;
cin >> s;
while (s < 7 || s % 2 == 0 || s < 0) {
cout << "Invalid size. Enter the size again: " << endl;
cin >> s;
}
cout << "Enter the letter: " << endl;
cin >> l;
while (l != 'c') {
cout << "Invalid letter. Enter the letter again: " << endl;
cin >> l;
}
if (l == 'c') {
int size = s;
for (int row = 0; row < size; row++) {
cout << "*";
for (int col = 0; col < size - 1; col++) {
if (row == size - 1)
cout << "*";
else
cout << " ";
if (row == 0)
cout << "*";
else
cout << " ";
}
cout << endl;
}
}
} while (choice == 'N');
return 0;
}
You're using choice without reading into it. Additionally, the check while (choice == 'N') doesn't make sense, you want to continue while the choice is no?
Here's the gist of it with the irrelevant parts cut for brevity.
#include <iostream>
int main() {
char choice{};
std::cout << "Welcome to the letter printer.\n";
do {
int s{};
std::cout << "Enter the size: " << std::flush;
std::cin >> s;
// ... check for size ...
char l{};
std::cout << "Enter the letter: " << std::flush;
std::cin >> l;
// ... check for letter ... draw letter ...
std::cout << "would you like to continue? (Y/N): " << std::flush;
std::cin >> choice;
} while (choice == 'Y');
}
For future reference, most of the code in your question isn't directly relevant to the problem, the restrictions on what letters to enter, the size restriction, and the drawing of the letter could all be left out when making your example. Doing this tends to reveal the problem.
I have fixed your code and in the meantime I want to make a few remarks for the future.
Before posting to StackOverflow asking for debugging, debug it yourself. I understand sometimes you may have a sore head from looking at the same code for a long time but not everyone likes debugging code here.
Have some decency and post code that is at the least functioning to some degree. It is a complete pain trying to find curly braces, commas, etc. that you should have found yourself.
Next time isolate your problem in your code before posting it here.
Regarding your code, you were thinking in the right direction.
In while(choice == 'N') [As pointed out by Raindrop7 & Ryan Haining], your char choice was undeclared. Simple fix is to declare / use the variable like cin >> choice in the example below.
Name your variables with sense, it s hard to keep track of a variable when it is being used everywhere e.g. [char s, int l].
Encapsulate code if it is being reused a lot e.g. [void PrintLetter(char, int)]
Side Note: Next time you encounter a bug. Put some kind of animal toy beside you and speak your problem out to it. Usually you'll answer your own question.
#include "stdafx.h"
#include <iostream>
using namespace std;
void PrintLetter(char letter, int size)
{
switch (letter)
{
case 'c':
for (int row = 0; row < size; row++)
{
cout << "*";
for (int col = 0; col < size - 1; col++)
{
if (row == size - 1)
{
cout << "*";
}
else
{
cout << " ";
}
if (row == 0)
{
cout << "*";
}
else
{
cout << " ";
}
cout << endl;
}
}
break;
case 'f':
break;
case 'l':
break;
}
}
int main() {
int size;
char letter;
char choice;
cout << "Welcome to the letter printer." << endl;
do {
cout << "Enter the size: " << endl;
cin >> size;
while (size < 7 || size % 2 == 0 || size < 0) {
cout << "Invalid size. Enter the size again: " << endl;
cin >> size;
}
cout << "Enter the letter: " << endl;
cin >> letter;
while (letter != 'c') {
cout << "Invalid letter. Enter the letter again: " << endl;
cin >> letter;
}
PrintLetter(letter, size); // Print Letter In Here, Function At The Top
cout << "Would you like to continue? [Y,N]" << endl;
cin >> choice;
}while (choice == 'Y' || choice == 'y'); // End Do While
return 0;
} // End Main

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;
}