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.
Related
Im new at programming and for homework, my teacher ask me to make an option menu that does different things, but I have a problem, case 5 is supposed to end the program, but if I select 5, the do-while cycle keeps asking me if I want to do something else, when I need that if I choose 5, the program ends, how can I end with the cycle and put the option to exit the program?
Thanks, and any help is welcome
#include <iostream>
#include <stdio.h>
#include <time.h>
#include <conio.h>
using namespace std;
int main() {
string name, lname;
int an, result;
int num;
char option;
int n, x;
time_t t, b;
char* f;
int flag = 0;
int i = 0;
do {
cout << "Option Menu";
cout << "\n1) Name and your last name";
cout << "\n2) Years of life";
cout << "\n3) First 100 numbers divisible by 3";
cout << "\n4) Date and hour";
cout << "\n5) Exit\n";
cin >> num;
switch (num) {
case 1:
cout << "\nWrite your name: ";
cin >> name;
cout << "\nWrite your last name: ";
cin >> lname;
cout << "\nYour complete name is: " << name << " " << lname;
break;
case 2:
cout << "\nWhat year you were born?: ";
cin >> an;
result = 2019 - an;
cout << "\nYou have " << result << " years\n";
break;
case 3:
for (i = 0; flag < 100; i++) {
if (i % 3 == 0) {
cout << i << "\n";
flag++;
}
}
break;
case 4:
b = time(&t);
f = ctime(&b);
printf("%s\n", f);
getch();
break;
}
cout << "\n Do you want to do something else?: ";
cin >> option;
} while (option == 's' or option == 'S');
cout << "\nGood bye :)" << endl;
system("pause");
return 0;
}
It's probably easiest to just simply use the if statement to check if num == 5 outside the switch statement and break the while loop when num is equal to 5.
#include <iostream>
#include <stdio.h>
#include <time.h>
#include <conio.h>
using namespace std;
int main() {
string name, lname;
int an, result;
int num;
char option;
int n, x;
time_t t, b;
char* f;
int flag = 0;
int i = 0;
do {
cout << "Option Menu";
cout << "\n1) Name and your last name";
cout << "\n2) Years of life";
cout << "\n3) First 100 numbers divisible by 3";
cout << "\n4) Date and hour";
cout << "\n5) Exit\n";
cin >> num;
switch (num) {
case 1:
cout << "\nWrite your name: ";
cin >> name;
cout << "\nWrite your last name: ";
cin >> lname;
cout << "\nYour complete name is: " << name << " " << lname;
break;
case 2:
cout << "\nWhat year you were born?: ";
cin >> an;
result = 2019 - an;
cout << "\nYou have " << result << " years\n";
break;
case 3:
for (i = 0; flag < 100; i++) {
if (i % 3 == 0) {
cout << i << "\n";
flag++;
}
}
break;
case 4:
b = time(&t);
f = ctime(&b);
printf("%s\n", f);
getch();
break;
}
if (num == 5) {
break;
}
cout << "\n Do you want to do something else?: ";
cin >> option;
} while (option == 's' || option == 'S');
cout << "\nGood bye :)" << endl;
system("pause");
return 0;
}
To accomplish this task, your switch must have either a case 5: or a default: block which assigns a value other than s or S to the option variable. That will allow your program to break out of the do..while loop.
There is another problem though. The user will still be asked if he wants to do something else even if they chose the Exit option. To avoid this, you can use an extra variable (for example, a userExits boolean) to skip the part where the program asks for input after the switch.
Here is a possible solution:
// after all the variable declarations
bool userExits = false;
do {
// All menu options
cin >> num;
switch (num) {
// (...)
case 4:
b = time(&t);
f = ctime(&b);
printf("%s\n", f);
getch();
break;
case 5:
userExits = true;
break;
}
if (userExits){
option = "exit";
}
else{
cout << "\n Do you want to do something else?: ";
cin >> option;
}
} while (option == 's' or option == 'S');
cout << "\nGood bye :)" << endl;
Sorry if I fail to be clear enough or make any mistakes, this is my first time posting.
My code runs without errors when complied but the first while loop (in int main) gets stuck looping whenever a user types a letter (like "a") for cin >> select; instead of the required 1, 2, or 3.
However, when I input "4" or any other random string of numbers, it runs fine and goes to my error message like it should.
Why is this and what can I do to make it run normally? (run the error message in response to letters entered as if they were numbers).
My code:
#include <iostream>
#include <string>
using namespace std;
void calculator();
void unavailableitem();
int main()
{
string select;
while (true)
{
cout << "\t[Main Menu]\n";
cout << " 1. Calculator\n";
cout << " 2. [unavailable]\n";
cout << " 3. [unavailable]\n";
cout << "\n Enter the number of your selection: ";
cin >> select;
if (select == "1")
{
cout << endl;
calculator();
break;
}
else if (select == "2")
{
unavailableitem();
break;
}
else if (select == "3")
{
unavailableitem();
break;
}
else
cout << "\nInvalid response.\n";
}
}
void unavailableitem()
{
string react;
cout << "\n \t [ITEM UNAVAILABLE]\n";
while (true)
{
cout << "\nEnter 'menu' to return to main menu: ";
cin >> react;
if (react == "menu")
{
cout << endl;
main();
break;
}
else
cout << "\nInvalid response.\n";
}
}
void calculator()
{
int choice;
double num1;
double num2;
double answer;
string choicesymbol;
cout << "List of operations:\n";
cout << " 1. Addition\n";
cout << " 2. Subtraction\n";
cout << " 3. Multiplication\n";
cout << " 4. Division\n";
cout << "Enter the number on the left to pick an operation: ";
cin >> choice;
cout << "\nEnter number 1: ";
cin >> num1;
cout << "\nEnter number 2: ";
cin >> num2;
if (choice == 1)
{
answer = num1 + num2;
choicesymbol = " + ";
}
if (choice == 2)
{
answer = num1 - num2;
choicesymbol = " - ";
}
if (choice == 3)
{
answer = num1 * num2;
choicesymbol = " * ";
}
if (choice == 4)
{
answer = num1 / num2;
choicesymbol = " / ";
}
cout << endl;
cout << num1 << choicesymbol << num2 << " = " << answer;
}
New code:
#include <iostream>
#include <string>
using namespace std;
void calculator();
void unavailableitem();
int main()
{
int select;
while (true)
{
cout << "\t[Main Menu]\n";
cout << " 1. Calculator\n";
cout << " 2. [unavailable]\n";
cout << " 3. [unavailable]\n";
cout << "\n Enter the number of your selection: ";
cin >> select;
if(!(cin >> select))
{
cout << "Input must be an integer.\n";
cin.clear();
continue;
}
else if (select == 1)
{
cout << endl;
calculator();
break;
}
else if (select == 2)
{
unavailableitem();
break;
}
else if (select == 3)
{
unavailableitem();
break;
}
}
}
void unavailableitem()
{
string react;
cout << "\n \t [ITEM UNAVAILABLE]\n";
while (true)
{
cout << "\nEnter 'menu' to return to main menu: ";
cin >> react;
if (react == "menu")
{
cout << endl;
return;
break;
}
else
cout << "\nInvalid response.\n";
}
}
void calculator()
{
int choice;
double num1;
double num2;
double answer;
string choicesymbol;
cout << "List of operations:\n";
cout << " 1. Addition\n";
cout << " 2. Subtraction\n";
cout << " 3. Multiplication\n";
cout << " 4. Division\n";
cout << "Enter the number on the left to pick an operation: ";
cin >> choice;
cout << "\nEnter number 1: ";
cin >> num1;
cout << "\nEnter number 2: ";
cin >> num2;
if (choice == 1)
{
answer = num1 + num2;
choicesymbol = " + ";
}
if (choice == 2)
{
answer = num1 - num2;
choicesymbol = " - ";
}
if (choice == 3)
{
answer = num1 * num2;
choicesymbol = " * ";
}
if (choice == 4)
{
answer = num1 / num2;
choicesymbol = " / ";
}
cout << endl;
cout << num1 << choicesymbol << num2 << " = " << answer;
}
Ad Ed Heal mentioned, the issue here is cin's failbit. When you do cin >> choice, and the user types "a", then the conversion to int fails. This sets cin's failbit, making all future reads from it fail until the failbit is cleared. So the next time you reach cin >> choice, the user won't even get to type anything.
You can use cin.clear() to restore to working order.
To do this a bit more robustly, you could do something like
while(true)
{
cout >> "Enter choice [1-4]: ";
if(!(cin >> choice))
{
cout << "Input must be an integer.\n";
cin.clear();
continue;
}
do_stuff_with_choice();
}
I am a newbie to programming in general, but playing with your code and looking up stuff made me find some sort of solution.
The cin.clear only clears the error log of the input, and I believe that it still retains the value of the letter.
What you should add right after is a cin.ignore(#,'\n') (# being a very, very large number) to have it avoid the line and skip right through it.
Found the solution in another question that explains the use of both cin commands.
I have this program in C++ for Student Management System , Everything is working fine , except one place where i try to delete a student based on his roll number .
What it should do : After asking the roll number search the record and delete it
What is it doing : It deletes all the other records which do not match that roll number
Here is my code :
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <conio.h>
#include <iomanip>
using namespace std;
int main() {
FILE *fp, *ft;
char another, choice;
struct student {
char first_name[50], last_name[50];
int roll_num; //new code added
char course[100];
int section;
};
struct student e;
char xfirst_name[50], xlast_name[50];
int xroll_num ; // new code added
long int recsize;
fp=fopen("users.txt","rb+");
if (fp == NULL) {
fp = fopen("users.txt","wb+");
if (fp==NULL)
{
puts("Cannot open file");
return 0;
}
}
recsize = sizeof(e);
while(1) {
system("cls");
cout << "\t\t====== STUDENT INFORMATION SYSTEM ======";
cout <<"\n\n ";
cout << "\n\n";
cout<<" \n\t\t\t======================";
cout << "\n \t\t\t 1. Add Records";
cout << "\n \t\t\t 2. List Records";
cout << "\n \t\t\t 3. Modify Records";
cout << "\n \t\t\t 4. Delete Records";
cout << "\n \t\t\t 5. Exit Program";
cout<<" \n\t\t\t======================";
cout << "\n\n";
cout << "\t\t\t Select Your Choice ::";
fflush(stdin);
choice = _getche();
switch(choice)
{
case '1' :
fseek(fp,0,SEEK_END);
another ='Y';
while(another == 'Y' || another == 'y')
{
system("cls");
cout << "Enter the First Name : ";
cin >> e.first_name;
cout << "Enter the Last Name : ";
cin >> e.last_name;
cout << "Enter the Course : ";
cin >> e.course;
cout << "Enter the Section : ";
cin >> e.section;
cout << "Enter the roll number :";
cin >> e.roll_num;
fwrite(&e,recsize,1,fp);
cout << "\n Add Another Record (Y/N) ";
fflush(stdin);
another = getchar();
}
break;
case '2':
system("cls");
rewind(fp);
cout << "=== View the Records in the Database ===";
cout << "\n";
while (fread(&e,recsize,1,fp) == 1){
cout << "\n";
cout <<"\nName :: " <<e.first_name <<" "<<e.last_name;
//cout << "\n";
cout <<"\nRoll Number :: " << e.roll_num ;
cout <<"\nCourse :: " <<e.course ;
cout <<"\nSection :: "<<e.section;
}
cout << "\n\n";
system("pause");
break;
case '3' :
system("cls");
another = 'Y';
while (another == 'Y'|| another == 'y')
{
// cout << "\n Enter the last name of the student : ";
cout << "\n Enter the Roll number of the student : ";
cin >> xroll_num;
rewind(fp);
while (fread(&e,recsize,1,fp) == 1)
{
//if (strcmp(e.last_name,xlast_name) == 0)
if(e.roll_num == xroll_num )
{
cout << "Enter the new Firt Name : ";
cin >> e.first_name;
cout << "Enter the new Last Name : ";
cin >> e.last_name;
cout << "Enter the new Roll Number : ";
cin >> e.roll_num;
cout << "Enter the new Course : ";
cin >> e.course;
cout << "Enter the new Section : ";
cin >> e.section;
fseek(fp, - recsize, SEEK_CUR);
fwrite(&e,recsize,1,fp);
break;
}
else
cout<<"record not found";
}
cout << "\n Modify Another Record (Y/N) ";
fflush(stdin);
another = getchar();
}
break;
case '4':
system("cls");
another = 'Y';
while (another == 'Y'|| another == 'y')
{
// cout << "\n Enter the last name of the student to delete : ";
cout <<"\n Enter the roll number of the student to delete : ";
cin >> xroll_num;
ft = fopen("temp.dat", "wb");
rewind(fp);
while (fread (&e, recsize,1,fp) == 1)
// if (strcmp(e.last_name,xlast_name) != 0)
if(e.roll_num == xroll_num )
{
fwrite(&e,recsize,1,ft);
}
fclose(fp);
fclose(ft);
remove("users.txt");
rename("temp.dat","users.txt");
fp=fopen("users.txt","rb+");
cout << "\n Delete Another Record (Y/N) ";
fflush(stdin);
another = getchar();
}
break;
case '5':
fclose(fp);
cout << "\n\n";
cout << "\t\t THANK YOU FOR USING THIS SOFTWARE";
cout << "\n\n";
exit(0);
}
}
system("pause");
return 0;
}
It deletes all the other records which do not match that roll number
Well you're only writing the records that match the roll number to the temp file, and then using that file to overwrite the users.txt file
if (e.roll_num == xroll_num) {
fwrite(&e, recsize, 1, ft);
}
I suppose what you really wanted to do is
if (e.roll_num != xroll_num) {
fwrite(&e, recsize, 1, ft);
}
You should probably read a good C++ i/o tutorial, as your code is mostly C. Consider writing your student struct as simple text instead of writing it wholesale to the file.
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);
when press "1" to start the game a error message comes up first instead of playing the game and then I have to enter "1" 3 times before the game starts and also the quit game option only works when you select "2" first if its not selected first it just comes up as a error message I cant see why it does this can anyone help me please ?
#include "Questions.h"
#include <iostream>
using namespace std;
const int MAXITEMS = 10;
int main ()
{
string question[MAXITEMS] = {"How man cards in a suit",
"How_many_suits_are_there_in_a_standard_pack_of_card",
"How_many_kings_are_in_a_standard_pack_of_cards"};
string answers[MAXITEMS] = {"4", "5", "6"};
int userInput = 0;
int tries = 0;
bool isGameOver = false;
cout << "select 1 to start game" << endl; //gives option to start and quit game
cout << "select 2 to quit game" << endl;
cin >> userInput;
if (userInput == 2)
{
isGameOver = true;
return 0;
};
// when game starts gives option to select question and shows all questions
do
{
if (userInput != 1||2)
{
cout << " Your input is not valid! please try again:" << endl;
// try switch cases for the different outcomes
cout << "select 1 to start game" << endl;
cout << "select 2 to quit game" << endl;
cin >> userInput;
while (!(cin >> userInput))
{
cin.clear(); // clear the error flags
cin.ignore(INT_MAX, '\n'); // discard the row
cout << "Your input is not valid! please try again: ";
cout << "select 1 to start game" << endl;
cout << "select 2 to quit game" << endl;
}
cout << userInput << endl;
}
// reprisent all characters as number to stop while roblem
if(userInput == 1)
{
do
{
cout << "select question" << endl;
for(int i = 0; i != MAXITEMS; i++)
{
cout << i << " " << question[i] << endl;
}
int selectQestion;
cin >> selectQestion;
if(selectQestion == 0||1||2 && tries != 2)
{
cout << "Enter your answer" << endl;
string userAnswer;
cin >> userAnswer;
while (!(cin >> userAnswer))
{
cin.clear(); // clear the error flags
cin.ignore(INT_MAX, '\n');
// discard the row
cout << "Your input is not valid!
please try again: ";
}
if (userAnswer == answers[0])
{
cout << "Correct answer" << endl;
}
else{
cout << "incorrect try again" << endl;
tries++;
cin >> userAnswer;
if (userAnswer == answers[0])
{
cout << "Correct answer" << endl;
}
else
cout << "Incorrect" << endl;
}
}
if (selectQestion == 0 ||1 ||2 && tries == 2)
{
cout << "you can no longer answer this question" << endl;
cout << "try another question" << endl;
}
}
while(userInput == 1);
}
}
while(isGameOver == false);
}
// add stuct or class to handle questions,
if (userInput != 1||2) doesn't do what you think. With the proper paretheses inserted, it is
if ((userInput != 1) || 2)
and 2 is nonzero, hence the condition is always true.
You want
if (userInput != 1 && userInput != 2)
The problem lies here:
if (UserInput!=1||2)
In this line, there are two conditions:
UserInput!=1 , 2
Here , whether user input is 1/2, the second condition 2 is always evaluated as true, which runs the if block
So change it to
if (UserInput!=1 && UserInput!=2)