#include <iostream>
using namespace std;
bool play_game(int n) {
int guess;
bool noguesses = false;
int numofguesses = 0;
cout << "Welcome to my number guessing game\n";
while (n!=guess && !noguesses)
{
if (numofguesses < 6)
{
cout << "\n";
cout << "Enter your guess: ";
cin >> guess;
cout << "\n";
cout << "You entered: " << guess;
numofguesses++;
return false;
}
else
{
oog = true;
}
}
if (noguesses) {
cout << "I'm sorry. You didn't find my number.\n";
cout << "It was" << n << endl;
}
else
{
cout << "\n";
cout << "You found it in" << numofguesses << "guess(es)\n";
return true;
}
}
int main()
{
int secretnum = 5;
play_game(secretnum);
}
When I run this, the program stops after cout << "You entered: " << guess;. I want it to keep looping until the number of guesses reaches 6, or until the user inputs the correct answer.
Remove return false;
if (numofguesses < 6)
{
cout << "\n";
cout << "Enter your guess: ";
cin >> guess;
cout << "\n";
cout << "You entered: " << guess;
numofguesses++;
return false; //Remove this line
}
Related
Sometimes when I run the program, it runs perfectly fine. Sometimes I get an infinite loop that just keeps displaying my first choice menu. I tried searching for the error and I couldn't figure it out. I thought there was an error in my input statement when I got the menuChoice, but I was unable to troubleshoot it out. Should I be checking the value of menuChoice more often? To better specify, I am referring to the second do-while loop, the one that reprints the menu choices after each iteration.
main.cpp
#include <vector>
#include <fstream>
#include <iostream>
#include "course.hpp"
using namespace std;
int main() {
int menuChoice, searchMenuChoice;
string fileName;
string line;
ifstream inStream;
string searchName;
string searchPrefix;
int searchNum;
vector<Course> courseList;
vector<int> enrolledClasses;
do{
cout << "Please enter the file that contains othe course data: ";
cin >> fileName;
inStream.open(fileName);
}while (!inStream.is_open());
cout << endl;
while (getline(inStream, line)){
courseList.push_back(Course(line));
}
cout << "Welcome to Banner NE, short for Never Existed!" << endl;
do {
cout << "\n"<< "---------------------------------------------" << endl;
cout << "1 - List all available classes" << endl;
cout << "2 - Search for a course" << endl;
cout << "3 - View your current enrolled courses" << endl;
cout << "4 - Enroll in course" << endl;
cout << "5 - Exit" << endl;
cout << "Make your selection here: ";
cin >> menuChoice;
cout << endl;
if (menuChoice == 5){
cout << "Thank you for using Banner NE and have a nice day!" << endl;
return 0;
}
if (menuChoice == 2) {
cout << endl;
cout << "Would you like to search by" << endl;
cout << "1 - Course number" << endl;
cout << "2 - Available seats remaining" << endl;
cout << "3 - Instructor name" << endl;
cout << "4 - Course prefix" << endl;
cout << "Make your selection: ";
cin >> searchMenuChoice;
if (searchMenuChoice == 2) {
for (int i = 0; i < courseList.size(); i++){
if (courseList.at(i).getSeatsRemaining() > 0)
courseList.at(i).printCourse();
}
}
if (searchMenuChoice == 1) {
cout << "Please enter the course number: ";
cin >> searchNum;
for (int i = 0; i < courseList.size(); i++){
if (courseList.at(i).MatchesCourseNumberSearch(searchNum))
courseList.at(i).printCourse();
break;
}
}
if (searchMenuChoice == 3) {
cout << "Please enter the name of the instructor: ";
cin >> searchName;
for (int i = 0; i < courseList.size(); i++) {
if (courseList.at(i).MatchesInstructorSearch(searchName))
courseList.at(i).printCourse();
}
}
if (searchMenuChoice == 4){
cout << "Please enter the prefix you would like to search for: ";
cin >> searchPrefix;
for (int x = 0; x < courseList.size(); x++)
if (courseList.at(x).MatchesPrefix(searchPrefix))
courseList.at(x).printCourse();
}
}
if (menuChoice == 1) {
for (int x = 0; x < courseList.size(); x++){
cout << "ID: " << x << "\t";
courseList.at(x).printCourse();
cout << endl;
}
}
if (menuChoice == 4) {
int classEnrollment;
cout << "Please enter the ID number of the class you would like to enroll: ";
cin >> classEnrollment;
if (courseList.at(classEnrollment).Enroll()){
enrolledClasses.push_back(classEnrollment);
cout << "You have enrolled in ID " << classEnrollment << endl;
}
else
cout << "There was not enough space, sorry." << endl;
}
if (menuChoice == 3){
for (int i = 0; i < enrolledClasses.size(); i++){
courseList.at(enrolledClasses.at(i)).printCourse();
cout << endl;
}
if (enrolledClasses.size() == 0 )
cout << "You are not currently enrolled in any classes." << endl;
}
} while (menuChoice != 5);
return 0;
}
Really sorry if this is a dumb question. I know it must have a super easy solution but I've been staring at this for so long I can't see it. It doesn't help that I'm really new at this either.
Long story short for some reason entering an invalid input past the first time returns me back to my menu, and sometimes also asks me to enter weight immediately after instead of allowing me to enter a menu choice. It's just all around broken and I don't know why. Thanks.
#include <iostream>
#include <iomanip>
#include <limits>
using namespace std;
bool loopFlag = true;
bool loopFlagTwo = true;
int choice = 0;
int time = 0;
float weightPounds = 0;
float weight = 0;
const int BIKING = 8;
const int RUNNING = 10;
const int LIFTING = 3;
const float YOGA = 2.5;
int main()
{
cout << "Welcome to my Fitness Center" << endl;
do
{
cout << "\n\t____________________________________________________________" << endl;
cout << "\n\t\t\tMy Fitness Center" << endl;
cout << "\t\t\tActivity System" << endl;
cout << "\t____________________________________________________________" << endl;
cout << "\t\t\t Main Menu\n" << endl;
cout << "\t\t\t1) Stationary Bike" << endl;
cout << "\t\t\t2) Treadmill" << endl;
cout << "\t\t\t3) Weight Lifting" << endl;
cout << "\t\t\t4) Hatha Yoga" << endl;
cout << "\t\t\t5) End" << endl;
cout << "\t____________________________________________________________" << endl;
cout << "\n\nEnter the workout that you wish to track, or end to exit:" << endl;
do
{
cin >> choice;
if (cin.fail() || choice > 5 || choice < 1)
{
cout << "Invalid choice. Please choose from option 1 through 5." << endl;
cin.clear();
cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
}
else if (choice == 5)
{
return 0;
}
else
{
loopFlag = false;
}
}
while (loopFlag);
do
{
cout << "\nPlease enter your weight in pounds: " << endl;
cin >> weightPounds;
if (cin.fail() || weightPounds <= 0)
{
cout << "Invalid weight entry!" << endl;
cin.clear();
cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
}
else
{
loopFlag = false;
}
}
while (loopFlag);
weight = weightPounds / 2.2;
cout << "\nYour weight is: \n" << fixed << setprecision(1) << weight << " kilograms." << endl;
if (choice == 1)
{
do
{
cout << "For how many minutes did you do this activity? " << endl;
cin >> time;
if (cin.fail() || time <= 0)
{
cout << "Invalid time entry!" << endl;
cin.clear();
cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
}
else
{
loopFlag = false;
}
}
while (loopFlag);
}
}
while (choice != 5);
return 0;
}
You need to set loopFlag to true before every do...while() you have, or use another flag, because after the first do...while(), loopFlag is always false.
So I'm working on this endterm project. Which the teacher said that we should use functions now. Which he recently introduced to us. My question is if it's a good idea to put every option into a function? Functions are for organizing and for code reuse right? Or I'm missing the point of functions. XD
What I mean is like making a function for option 1, which is add account. Instead of putting it in the main function. So far I only made a function for options 3,4 and 5. Which are search, view and delete functions
#include <iostream>
#include <string>
using namespace std;
bool accountSearch(int searchParameter);
void viewList();
void deleteFromList(int delParameter);
int option, numberOfAccounts = 0, accountNumSearch, index, deleteAccount;
struct personAccount
{
int currentBalance, accountNumber, pin;
string lastname, firstname, middlename;
};
personAccount account[20];
int main()
{
do{
cout << "[1] Add Account" << endl
<< "[2] Edit Account" << endl
<< "[3] Search Account" << endl
<< "[4] View Account" << endl
<< "[5] Delete Account" << endl
<< "[6] Inquire" << endl
<< "[7] Change Pin Number" << endl
<< "[8] Withdraw" << endl
<< "[9] Deposit" << endl
<< "[10] View Transactions" << endl
<< "[11] Exit" << endl << endl
<< "Option [1-11]: ";
cin >> option; cout << endl;
if(option == 1)
{
if(numberOfAccounts != 20)
{
cout << "Account Number: ";
cin >> account[numberOfAccounts].accountNumber;
cout << "PIN: ";
cin >> account[numberOfAccounts].pin;
cout << "Lastname: ";
cin >> account[numberOfAccounts].lastname;
cout << "Firstname: ";
cin >> account[numberOfAccounts].firstname;
cout << "Middlename: ";
cin >> account[numberOfAccounts].middlename;
account[numberOfAccounts].currentBalance = 0;
++numberOfAccounts;
cout << endl;
}
else
{
cout << "The list is full!\n\n";
}
}
else if(option == 2)
{
if(numberOfAccounts != 0)
{
cout << "Account Number: ";
cin >> accountNumSearch;
if(accountSearch(accountNumSearch))
{
cout << "PIN: ";
cin >> account[index].pin;
cout << "Lastname: ";
cin >> account[index].lastname;
cout << "First name: ";
cin >> account[index].firstname;
cout << "Middlename: ";
cin >> account[index].middlename;
cout << endl;
}
else
{
cout << "Account not found!\n\n";
}
}
else
{
cout << "The list is empty!\n\n";
}
}
else if(option == 3)
{
if(numberOfAccounts != 0)
{
cout << "Enter account number to search: ";
cin >> accountNumSearch;
if(accountSearch(accountNumSearch))
{
cout << "Found at index " << index << "\n\n";
}
else
{
cout << "Not found!\n\n";
}
}
else
{
cout << "The list is empty!\n\n";
}
}
else if(option == 4)
{
if(numberOfAccounts != 0)
{
viewList();
}
else
{
cout << "The list is empty!\n\n";
}
}
else if(option == 5)
{
if(numberOfAccounts != 0)
{
cout << "Account Number: ";
cin >> deleteAccount;
deleteFromList(deleteAccount);
}
}
}while(option != 11);
}
bool accountSearch(int searchParameter)
{
bool found = 0;
for(int i = 0; i < numberOfAccounts; i++)
{
index = i;
if (account[i].accountNumber == searchParameter)
{
found = 1;
break;
}
}
if(found)
{
return 1;
}
else
{
return 0;
}
}
void viewList()
{
for(int i = 0; i < numberOfAccounts; i++)
{
cout << "Account Number: " << account[i].accountNumber << endl
<< "Lastname: " << account[i].lastname << endl
<< "Firstname: " << account[i].firstname << endl
<< "Middlename: " << account[i].middlename << endl
<< "Current Balance: " << account[i].currentBalance << "\n\n";
}
}
void deleteFromList(int delParameter)
{
if(accountSearch(deleteAccount))
{
for(int i = index; i < numberOfAccounts; i++)
{
account[i] = account[i+1];
}
--numberOfAccounts;
cout << "Deleted Done\n";
}
else
{
cout << "Account not found!\n";
}
}
It's not done yet, but is there anything you would like to mention or suggest?
Yes, you should write functions separately, it's common good practice as a programmer, It will be easier for you(and others) to read, follow, and understand your code.
So, if your options do different things, they should have their own functions. (More like it would be desirable, in the end it's up to you)
my code compiles but it doesn't allow the user to guess the word correctly and when it displays the correct word, it is just a string of nonsense.
#include <iostream>
#include <fstream>
#include <string>
#include <ctime>
#include <cstdlib>
using namespace std;
int instructions();
void manual();
void file(char*);
int letterFill(char, char*, char*);
void Unknown(char*, char*);
const int MAX_LENGTH = 10;
void main()
{
bool done = false;
char word[MAX_LENGTH];
char unknown[MAX_LENGTH];
char letter;
char name[MAX_LENGTH];
int wrong_guesses = 0;
int MAX_TRIES;
char ans;
while (!done)
{
switch (instructions())
{
case 1:
{
manual();
break;
}
case 2:
{
file(word);
break;
}
}
cout << "WHAT IS THE NUMBER OF GUESSES ALLOWED?: " << endl;
cin >> MAX_TRIES;
Unknown(word, unknown);
cout << endl << endl << "HANGMAN";
cout << endl << endl << "Each letter is represented by a star." << endl;
cout << "You have " << MAX_TRIES << " tries left.";
cout << "ENTER GUESS WHEN READY: ";
cin >> letter;
while (letter != 'N' && letter != 'n')
{
while (wrong_guesses < MAX_TRIES)
{
cout << unknown << endl;
cout << "Guess a letter: " << flush;
cin >> letter;
if (letterFill(letter, word, unknown) == 0)
{
cout << endl << "You got it wrong! You lose a guess" << endl;
wrong_guesses++;
}
else
{
cout << endl << "Pfft, you got lucky" << endl;
}
cout << "Guesses Left: " << MAX_TRIES - wrong_guesses << endl;
if (strcmp(word, unknown) == 0)
{
cout << word << endl;
cout << "You got it!" << endl;
exit(0);
}
cout << "You've been hanged." << endl;
cout << "The word was : " << word << endl;
}
}
cout << "Try again? (y/n): " << flush;
cin >> ans;
if (ans == 'y' || ans == 'Y')
done = true;
else
done = false;
}
system("pause");
}
int instructions()
{
int select = 0;
cout << endl << "HANGMAN" << endl << endl;
cout << " PROGRAM MENU" << endl;
cout << " Select option 1 or 2" << endl << endl;
cout << " 1. INPUT WORD MANUALLY" << endl;
cout << " 2. PLAY AGAINST THE COMPUTER" << endl;
cout << " 3. EXIT PROGRAM BY INPUTING: N or n" << endl << endl;
cin >> select;
return select;
}
void manual()
{
string word;
cout << endl << "INPUT WORD: " << endl;
cin >> word;
return;
}
void file(char *roc)
{
ifstream fin("word.txt");
int x;
int count = 1;
int word;
int i = 0;
srand(time(0));
word = rand() % 20;
while (count < word)
{
fin >> x;
if (x == 0)
{
count++;
}
}
do
{
fin >> x;
roc[i++] = char(x);
} while (x);
return;
}
int letterFill(char guess, char *secretword, char *guessword)
{
int i;
int matches = 0;
for (i = 0; i<MAX_LENGTH; i++)
{
if (secretword[i] == 0)
{
break;
}
if (guess == guessword[i])
{
return 0;
}
if (guess == secretword[i])
{
guessword[i] = guess;
matches++;
}
}
return matches;
}
void Unknown(char *word, char *unknown)
{
int i;
int length = strlen(word);
for (i = 0; i<length; i++)
{
unknown[i] = '*';
}
unknown[i] = 0;
}
Again
my code compiles but it doesn't allow the user to guess the word correctly and when it displays the correct word, it is just a string of nonsense.
So, I have several fields to fill in with numerals. And if I try to fill in the input with letters (ex. 'noway' or 'gg1337' - it makes and error and asks for a valid number (without letters for ex. '13' or '1500000').
BUT there is one problem, if I start to fill the input with numbers and then I add some letters (for ex. '12nowshithappens'), this jumps to the next field of input, thinking it is a valid number, but showing an error in the next input field.
Here is the function code:
int appled()
{
cin >> appleds;
while(cin.fail())
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(),'\n');
cout << "An arror occured!\nPlease, enter a valid number: ";
cin >> appleds;
}
return appleds;
}
If I described something wrong - here is the full code of my test program :)
// exZerry presents
#include <iostream>
#include <conio.h>
int apples;
int fruit;
int oranges;
int x;
int appleds;
int orangeds;
using std::cout;
using std::cin;
using std::endl;
using std::numeric_limits;
using std::streamsize;
char newline = '\n';
bool ok;
bool ok2;
bool ok3;
int appled() //Function to receive 'apples' input
{
cin >> appleds;
while(cin.fail())
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(),'\n');
cout << "An arror occured!\nPlease, enter a valid number: ";
cin >> appleds;
}
return appleds;
}
int oranged() //Function to receive 'oranges' input
{
cin >> orangeds;
while(cin.fail())
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(),'\n');
cout << "An arror occured!\nPlease, enter a valid number: ";
cin >> orangeds;
}
return orangeds;
}
int main()
{
ok = ok2 = ok3 = false; //Some testing
while(!ok2) //Actual program loop
{
x = 0; // Dropping program restart.
//cout << "-----------------------" << endl;
//cout << "DEBUG MODE: " << x << endl;
//cout << "-----------------------" << endl;
cout << "=====================================================" << endl;
cout << "Enter apples: ";
apples = appled();
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(),'\n'); //Now we have apples
cout << "Enter oranges: ";
apples = oranged();
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(),'\n'); //And now we have oranges
cout << "\n=====================================================" << endl;
cout << "Calculating..." << endl;
cout << "=====================================================" << endl;
fruit = apples + oranges;
cout << "In total we have " << fruit << " fruit" << endl;
cout << "=====================================================" << endl;
cout << newline;
//Option to go out or continue the loop
//If you enter 1 - resets the program, any other char - exit
cout << "Go out? (1 - 'No', Others - 'Yeap'):" << " ";
cin >> x;
cout << newline;
// ok2 = true;
if (x == 1)
{
cout << "Continue the program..." << endl;
//cout << "-----------------------" << endl;
//cout << "DEBUG MODE: " << x << endl;
//cout << "-----------------------" << endl;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(),'\n');
ok = false;
ok3 = false;
continue;
}
if (x == 0)
{
cout << "Shutting down the app..." << x << endl;
//cout << "-----------------------" << endl;
//cout << "DEBUG MODE: " << x << endl;
//cout << "-----------------------" << endl;
break;
}
else
{
cout << "Shutting down the app..." << x << endl;
//cout << "-----------------------" << endl;
//cout << "DEBUG MODE: " << x << endl;
//cout << "-----------------------" << endl;
break;
}
}
cout << "Press any key to exit :D" << endl;
getch();
return 0;
}
You can make your own facet that parses character sequence like that add invalid. Like this:
class num_get : public std::num_get<char>
{
public:
iter_type do_get( iter_type it, iter_type end, std::ios_base& str,
std::ios_base::iostate& err, long& v) const
{
auto& ctype = std::use_facet<std::ctype<char>>(str.getloc());
it = std::num_get<char>::do_get(it, end, str, err, v);
if (it != end && !(err & std::ios_base::failbit)
&& ctype.is(ctype.alpha, *it))
err |= std::ios_base::failbit;
return it;
}
};
Now you can install it into your stream:
std::locale orig(std::cin.getloc());
std::cin.imbue(std::locale(orig, new num_get));
while (!(std::cin >> appleds)) {
// input was not entirely numeric
}
// input was entirely numeric
So I tried and it worked, thanks, Batmaaaan :D
Adding full working code. What's it doing? Simple: When you wish to count something and you obviously do not want to count letters in your program, this might help you to do it, while styding C++ or whatever. Some basics, I guess, for everyone =)
Made and tested in Visual Studio 2012. Took some time to gather every peace of code in one place.
// exZerry presents
// Apples & Oranges V2.1
#include <iostream>
#include <conio.h>
int apples;
int juce;
int oranges;
int x;
int appleds;
int orangeds;
using std::cout;
using std::cin;
using std::endl;
using std::numeric_limits;
using std::streamsize;
using std::locale;
char newline = '\n';
bool ok;
bool ok2;
bool ok3;
class num_get : public std::num_get<char>
{
public:
iter_type do_get( iter_type it, iter_type end, std::ios_base& str,
std::ios_base::iostate& err, long& v) const
{
auto& ctype = std::use_facet<std::ctype<char>>(str.getloc());
it = std::num_get<char>::do_get(it, end, str, err, v);
if (it != end && !(err & std::ios_base::failbit)
&& ctype.is(ctype.alpha, *it))
err |= std::ios_base::failbit;
return it;
}
};
/*
int appled()
{
cin >> appleds;
while(cin.fail())
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(),'\n');
cout << "An arror occured!\nPlease, enter a valid number: ";
cin >> appleds;
}
return appleds;
}
int oranged()
{
cin >> orangeds;
while(cin.fail())
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(),'\n');
cout << "An arror occured!\nPlease, enter a valid number: ";
cin >> orangeds;
}
return orangeds;
}
*/
int main()
{
cout << "=====================================================" << endl;
cout << "Welcome to exZerry's 'Apples & Oranges V2'" << endl;
cout << "=====================================================" << endl;
cout << newline;
cout << newline;
ok = ok2 = ok3 = false;
while(!ok2)
{
x = 0;
//cout << "-----------------------" << endl;
//cout << "DEBUG MODE: " << x << endl;
//cout << "-----------------------" << endl;
cout << "=====================================================" << endl;
cout << "Enter apples: ";
// apples = appled();
locale orig(cin.getloc());
cin.imbue(locale(orig, new num_get));
while (!(cin >> apples)) {
cout << "An arror occured!\nPlease, enter a valid number: ";
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(),'\n');
}
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(),'\n');
cout << "Enter oranges: ";
// oranges = oranged();
//std::locale orig(std::cin.getloc());
cin.imbue(locale(orig, new num_get));
while (!(cin >> oranges)) {
cout << "An arror occured!\nPlease, enter a valid number: ";
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(),'\n');
}
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(),'\n');
cout << "\n=====================================================" << endl;
cout << "Calculating..." << endl;
cout << "=====================================================" << endl;
juce = apples + oranges;
cout << "In total we have " << juce << " fruit" << endl;
cout << "=====================================================" << endl;
cout << newline;
cout << "Go out? (1 - 'No', Others - 'Yeap'):" << " ";
cin >> x;
cout << newline;
// ok2 = true;
if (x == 1)
{
cout << "Continue the program..." << endl;
//cout << "-----------------------" << endl;
//cout << "DEBUG MODE: " << x << endl;
//cout << "-----------------------" << endl;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(),'\n');
ok = false;
ok3 = false;
continue;
}
if (x == 0)
{
cout << "Shutting down the app..." << x << endl;
//cout << "-----------------------" << endl;
//cout << "DEBUG MODE: " << x << endl;
//cout << "-----------------------" << endl;
break;
}
else
{
cout << "Shutting down the app..." << x << endl;
//cout << "-----------------------" << endl;
//cout << "DEBUG MODE: " << x << endl;
//cout << "-----------------------" << endl;
break;
}
}
cout << "Press any key to exit :D" << endl;
getch();
return 0;
}