How to successfully restart loop and accept new responses? - c++

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

Related

How to make DUPLICATED ANSWERS wrong?

i am making a word guessing game in c++ (im new at programming btw) im just gonna ask how can i make the "already-answered" answers as wrong and cant get points from the same word again? here's my current code...
#include <iostream>
#include <string>
using namespace std;
int main()
{
int firstQPoint, secondQPoint, thirdQPoint, mane;
char yourChoice, levelChoice, goBack;
string yourFirstAnswer, yourSecondAnswer, yourThirdAnswer;
gameMenu:
cout << "\t GUESS THE WORD GAME";
cout << "\t\n\n MADE BY GROUP FIVE";
cout << "\t\t\n\n 1. PLAY | ENTER \"1\" TO PLAY ";
cout << "\t\t\n\n 2. QUIT | ENTER \"2\" TO QUIT ";
cout << "\t\t\n\n 3. RULES | ENTER \"3\" TO SEE THE RULES";
cout << "\t\t\n\n What Do You Want To Do : ";
cin >> yourChoice;
if (yourChoice == '1') {
cout << "\t GUESS THE WORD GAME";
cout << "\t\n\n MADE BY GROUP FIVE";
selectALevel:
cout << "\t\n\n OKAY, CHOOSE A LEVEL (1-3) : ";
cin >> levelChoice;
switch (levelChoice) {
case ('1'):
cout << "\t GUESS THE WORD GAME";
cout << "\t\n\n MADE BY GROUP FIVE";
cout << "\t\t\n\nGIVE 3 BODY PARTS THAT STARTS WITH LETTER \"T\"";
cout << "1 : ";
cin >> yourFirstAnswer;
if (yourFirstAnswer == "TOE", "TONGUE", "TOOTH") {
cout << "\n\n\t\tNICE, YOU GOT A POINT!";
firstQPoint = 1 + 0;
}
cout << "2 : ";
cin >> yourSecondAnswer;
if (yourSecondAnswer == "TOE", "TONGUE", "TOOTH") {
cout << "\n\n\t\tNICE, YOU GOT A POINT!";
secondQPoint = 1 + firstQPoint;
}
cout << "3 : ";
cin >> yourThirdAnswer;
if (yourThirdAnswer == "TOE", "TONGUE", "TOOTH") {
cout << "\n\n\t\tNICE, YOU GOT A POINT!";
thirdQPoint = 1 + secondQPoint;
}
break;
case ('2'):
break;
case ('3'):
break;
default:
goto selectALevel;
}
}
else if (yourChoice == '3') {
do {
cout << "\t GUESS THE WORD RULES";
cout << "\t\t\n\n1. ONLY USE UPPERCASE LETTERS";
cout << "\t\t\n\n1. ONLY USE SINGULAR WORDS";
cout << "\t\t\n\n ENTER \"1\" TO GO BACK : ";
cin >> goBack;
if (goBack == '1') {
goto gameMenu;
}
} while (goBack != '1');
}
else if (yourChoice == '2') {
cout << "\t\t\n\n Okay, Goodbye!";
}
return 0;
}
i tried the longer way, where i will manually code it like this
#include <iostream>
using namespace std;
int main()
{
int number, again;
cout << "give 2 number";
cin >> number;
cout << "again :";
cin >> again;
if (number == 1 && again == 2) {
cout << "correct";
else if (number == 2 && again == 1)
{
cout << "correct";
}
}
}
but it's very hard since im working with too many combinations! thanks in advance for answering!
Inside each switch case you can make a loop to repeat the question if the word is wrong.
At the beginning of the switch (before the loop) you can create an empty list where you will store every answer they give.
In the end you only need to make a function that goes through that same list and checks if a word is inside it or not.

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.

C++ While loop terminating even though conditions are not met

I want the program to keep asking for values to do calculations until the flag is true then the program must stop, but it only ever executes once. I don't know if I am using the char the right way or if there is a better way to do these types of while loops with flags. Any help would be great.[enter image description here][1]
int main()
{
displayMenu();
bool flag = false;
while(!flag)
{
int choice = 0; int val1 = 0; int val2 = 0; int ans = 0;
cout << "Enter your choice (1-5): ";
cin >> choice;
cout << "\nEnter integer 1: ";
cin >> val1;
cout << "\nEnter integer 2: ";
cin >> val2;
if(choice < 0 || choice > 5)
{
cout << "\nEnter a choice between 1-5: ";
cin >> choice;
}
if (choice == 1)
{
ans = Add(val1,val2);
cout << "\nResult: " << ans << endl;
}
if (choice == 2)
{
ans = Subtract(val1,val2);
cout << "\nResult: " << ans << endl;
}
if (choice == 3)
{
ans = Multiply(val1,val2);
cout << "\nResult: " << ans << endl;
}
if (choice == 4)
{
ans = Divide(val1,val2);
cout << "\nResult: " << ans << endl;
}
if (choice == 5)
{
ans = Modulus(val1,val2);
cout << "\nResult: " << ans << endl;
}
char c_flag[] = "n";
cout << "Press Y or y to continue: ";
cin >> c_flag;
if(c_flag == "y" || c_flag == "Y")
{
flag = false;
}
else
{
flag = true;
}
}
return 0;
}
With data type char c_flag[], condition c_flag == "y" will very likely never be met, because you are comparing two (different) pointer values, not their contents.
Use std::string c_flag instead, and at least your conditions should work as expected.
You could also write
char c_flag[] = "y";
...
if (strcmp(c_flag,"y")==0) ...
but I'd prefer the std::string-variant for following reason: with char c_flag[] = "y", you allocate an array of size 2 (including string termination character); With cin >> c_flag, if you enter more than one character, you will exceed array length and yield undefined behaviour. With std::string, in contrast, the variable will "grow" if necessary.

why am i getting so many numbers from my array c++

I'm still working on this project and I have most of my problems fixed.
The problem shows itself while using selection B, but lies in option A and sending the array to the .txt file. There are a lot of extra numbers being added to the .txt file. When I cout, it displays the numbers in the array like it should, but in the text file it looks like this
Anthony201910181114-8589934604445358131768008182078541176802418196927161130726102120444535893
everything before the - is correct, but all of these numbers after need to go.
Why is this happening and how can I fix this?
Thank you.
int main()
{
int Stats[6];
char Selection;
string Character1;
int i;
char keep;
do
{
cout << "Hello, welcome to my character generator. Please select an option" << endl;// Menu Options
cout << "A: Create Character Name and generate stats" << endl;
cout << "B: Display Name and Stats" << endl;
cout << "C: Quit" << endl;
cin >> Selection; // Menu Selection
cout << endl;
if ( (Selection == 'a') || (Selection == 'A') )// if user selects a, this happens
{
cout << "Welcome, Before you can start your adventures you must name your character." << endl;
do
{
cout << "Please enter your a name." << endl;// prompts user to enter a name for their Caracter
cin >> Character1;
cout << "Thank you now lets generate your stats." << endl;
for (i=0; i<6;i++)// I Want this to run the function GenerateScore() 6 times and input each result into the next element of Stats[6]
{
Stats[i]=GenerateScore();
}
for(i=0;i<6;i++)// displays your scores to the player.
{
cout << Stats[i]<< endl;
}
cout << "would you like to keep this name and these Stats?"<< endl;
cout << "Y/N" << endl;
cin >> keep;
break;
}
while ( (keep=='n') || (keep=='N') );
ofstream savecharinfo("charactersave.txt");// saves the Name and the filled array Stats[6] to the charactersave.txt file
if(savecharinfo.is_open())
{
savecharinfo << Character1;
for(int i = 0; i<6; i++)
{
savecharinfo << Stats[i];
}
}
else cout << "File could not be opened." << endl;
}
else if ( (Selection =='b') || (Selection == 'B') )
{
cout << " Welcome back, here are is your character." << endl;
ifstream displaycharacter("charactersave.txt");
if(displaycharacter.is_open())
{
while ( getline (displaycharacter,Character1) )
{
cout << Character1 << endl;
}
displaycharacter.close();
}
else cout << "File could not be opened";
}
else
break;
}
while ( (Selection != 'c') || (Selection == 'C') ); // ends the program is c or C is entered.
return 0;
}
int GenerateScore()
{
int roll1 = rand()%6+2;
int roll2 = rand()%6+2;
int roll3 = rand()%6+2;
int sum;
sum=roll1+roll2+roll3;
return sum;
}
Like was mentioned in the comments:
while ( (keep='n') || ('N') );
should (at least) be changed to
while ( (keep == 'n') || (keep == 'N') );
Also, this loop:
for(int i = 0; Stats[i]; i++)
Will only terminate when Stats[i] evaluates to false, which will only happen when Stats[i] == 0. This loop is causing the extra chars in the file: the code keeps accessing out of bounds array elements until randomly the out of bounds element == 0. You probably want for(int i = 0; i < 6; i++)

C++ exit loop not working

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