Basically, this program outputs what candy a person should have, based on their responses to the prompts. If they like chocolate, the program asks if they like nuts. If they say yes to chocolate and no to nuts, they get M&M's. If they say yes to chocolate and nuts, they get peanut M&Ms. If they say no to chocolate, they get Skittles.
No matter what I put in for chocLover, I get Skittles as the output.
Source code:
#include <iostream>
#include <iomanip>
#include <cstring>
using namespace std;
int main()
{
const int SNACK_SIZE = 15;
const int DRINK_SIZE = 6;
char guestName[30];
int guestAge;
char chocLover;
char nutLover;
int count;
char snack[15];
char drink[6];
for(count = 1; count <=12; count=count+1)
{
cout << left << "Guest #" << count << ":" << endl;
cout << setw(31) << "What is your friend's name?";
cin.getline(guestName,30);
cout << setw(31) << "How old is your friend?";
cin >> guestAge;
cout << setw(31) << "Do they like chocolate (Y/N)?";
cin.get(chocLover);
cin.ignore(1000,'\n');
if(chocLover == 'Y')
{
cout << setw(31) << "Do they like nuts (Y/N)?";
cin.get(nutLover);
if(nutLover == 'Y')
{
strncpy(snack,"Peanut M & M\'s",SNACK_SIZE);
}
else
{
strncpy(snack,"M & M\'s",SNACK_SIZE);
}
}
else
{
strncpy(snack,"Skittles",SNACK_SIZE);
}
if(guestAge <= 21)
{
if(guestAge < 6)
{
strncpy(drink,"juice",DRINK_SIZE);
}
else
{
strncpy(drink,"soda",DRINK_SIZE);
}
}
else
{
strncpy(drink,"wine",DRINK_SIZE);
}
cout << endl;
cout << "You should serve " << guestName << " " << snack << " and ";
cout << drink << "." << endl << endl << endl;
}
return 0;
}
Output:
Guest #1:
What is your friend's name? Guest
How old is your friend? 18
Do they like chocolate (Y/N)? Y
You should serve Guest Skittles and soda.
Guest #2:
What is your friend's name? Guest
How old is your friend? 20
Do they like chocolate (Y/N)? Y
You should serve Guest Skittles and soda.
And so forth until it reaches #12.
If I cout << chocLover; nothing prints as well.
cin.get(chocLover) performs unformatted input, it's reading the newline that was entered as part of the previous input. Use a formatted input operator to ignore whitespace:
cin >> chocLover;
Related
I am currently working on a (very very basic) program that is a tutorial for programming( ironic given my knowledge, I know). I was instructed to modularize my code so that each unit is in its own module. I'm guessing that means adding headers? I'm working with Visual Studios, if that helps at all. I've included my code below to help my bad explanation make sense. Thanks for any help you can provide!
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
int Total;
int ans;
class Question
{
private:
string Question_Text;
string Answer_one;
string Answer_two;
string Answer_three;
int Correct_Answer;
int Question_Score;
public:
void setValues(string, string, string, string, int, int);
void askQuestion();
};
int main()
{
string username = "";
char choice=' ';
char c;
int x = 4;
int y = 5;
int z = x + y;
//welcome message
cout << "Hello user, please enter your name:";
cin >> username;
cout << "Welcome to the programming tutorial " << username << "." << endl;
//menu selection
while(choice != '5')
{
cout << "What would you like to do? (Unit 1 - Declaring Variables (1), Unit 2 - Input/ Output (2), Unit 3 - Conditionals (3), Quizzes (4) or Exit (5))";
cin >> choice;
if (choice == '1')
{
cout << "We will begin with defining variables. The first step to doing this is choosing which datatype your variable is.\n";
cout << "The following are a few of the common datatypes used in programming.\n";
cout << "Character ==> char\n";
cout << "Integer ==> int, long, double\n";
cout << "Boolean ==> bool\n";
cout << endl;
cout << "When declaring a variable, you must put its datatype before the variable name.\n";
cout << "An example of this would be if we wanted to declare the value of x as 4.\n";
cout << "We would write this as: \n";
cout << "int x = 4\n";
cout << "The program will now use the value 4 for the variable name 'x'\n";
cout << endl;
cout << "Now let's assume we assigned the value of 5 to the variable 'y'\n";
cout << "If we wanted to add x and y and assign the sum to the variable 'z', we would write:\n";
cout << "int z = x + y\n";
cout << "Now when we use the variable 'z' in our program, it will perform the calculation given x=4 and y=5 and declare 9 as the value of the variable 'z'.\n";
cout << "To test our code, we would write: " << endl;
cout << "cout<<'x + y'<< z << endl; \n";
cout << "If written correctly, it will display as: \n";
cout << "x + y = " << z << "." << endl;
}
if (choice == '2')
{
cout << "Now that we understand the basics of declaring variables, let's discuss displaying, or output of, information to a user.\n";
cout << "If you wanted to display a welcome message, for example, you would type:\n";
cout << "cout << 'Welcome';\n";
cout << "The line of code would start with 'cout' followed by two less than signs and then the message you wish to display in quotes.\n";
cout << "Using this, you can ask the user for input.\n";
cout << "Enter c to continue...";
cin >> c;
cout << "Let's say we have a program that flips a coin. You may want to ask the user how many times to flip the coin.\n";
cout << "Assuming we previously declared this amount variable as 'int timesFlipped', we would 'cout' our question and the next line would read:\n";
cout << "cin>> timesFlipped; \n";
cout << "This will store the users input for the variable 'timesFlipped'\n";
cout << "You almost always end a line of code with a semi colon." << endl;
}
if (choice == '3')
{
cout << "This unit will cover conditional expressions." << endl;
}
if (choice == '4')
{
string Question_Text;
string Answer_one;
string Answer_two;
string Answer_three;
int Correct_Answer;
int Question_Score;
Question q1;
Question q2;
Question q3;
cout << username << ", you have chosen to take a quiz." << endl << endl;
int ans, score = 0;
cout << "Unit One Quiz - Variables " << endl << endl;
q1.setValues("How would you declare the value of 'x' as 12? ",
"x=12()",
"x==12()",
"x=12;()",
3,
1);
q2.setValues("What do you need to put before a variable when declaring it?",
"a name()",
"a value()",
"a datatype()",
3,
1);
q3.setValues("Which data type would you use for a number that includes a decimal value?",
"int()",
"double()",
"float()",
2,
1);
q1.askQuestion();
q2.askQuestion();
q3.askQuestion();
cout << "Your score out of a possible 3 is " << Total << endl;
}
if (choice == 'E')
{
cout << "Have a good day!";
break;
}
}
system("pause");
}
void Question::setValues(string q, string a1, string a2, string a3, int ca, int pa)
{
Question_Text = q;
Answer_one = a1;
Answer_two = a2;
Answer_three = a3;
Correct_Answer = ca;
Question_Score = pa;
}
void Question::askQuestion()
{
cout << endl;
cout << Question_Text << endl;
cout << "1. " << Answer_one << endl;
cout << "2. " << Answer_two << endl;
cout << "3. " << Answer_three << endl << endl;
cout << "Please enter your answer: " << endl;
cin >> ans;
if (ans == Correct_Answer)
{
cout << "That is correct!" << endl;
Total = Total + Question_Score;
}
else
{
cout << "Sorry, that is incorrect" << endl;
cout << "The correct answer was " << Correct_Answer << endl;
}
}
I'm guessing that means adding headers?
That's pretty much the idea.
In your case, you may want to:
Create a header name Question.h that includes the declaration of class Question.
Create a source file name Question.cpp and move the class definition there, ie all functions like void Question::askQuestion() etc.
Create a test file name test.cpp to put your main function, and remember to include the Question.h
As you are using Visual Studio, you can create a Project in advance then add all those files before compiling/building.
I'm trying to make a little game, and I'm a beginner.
The problem is the parts with the ifs and the else, where it says "Lady" and "Sir".
#include <iostream>
#include <string>
using namespace std;
int main()
{
string playerName;
int age;
int playerGender;
cout << "Are you a Lady or a Sir?" << endl;
cin >> playerGender;
if (playerGender = Lady)
{
cout << "So you're a girl. " << endl;
}
else if (playerGender = Sir)
{
cout << "So you're a boy." << endl;
}
cout << "What is your name " << playerGender << "?" << endl;
cin >> playerName;
cout << "What is your age?" << playerName << endl;
cin >> age;
if (age <= 10)
{
cout << "You're too young " << playerName << "! " << endl;
}
else if (age >= 11)
{
cout << "You are old enough to play" << playerName << ". " << endl;
That's what I have, I don't know whats wrong. Help please!
When you perform the following:
std::cin >> playerGender;
You are retrieving a number from the user. You are then assigning that number to your playerGender with the following:
if (playerGender = Lady)
You're only using a single =, which assigns the value that's in Lady to playerGender. You probably mean to write == which will compare the value of playerGender and Lady.
I can't tell what Lady and Sir are, but for your purposes you will need to ensure they are an int:
const int Lady = 0, Sir = 1;
Or an enum:
enum genders { Lady = 0, Sir = 1 };
Now you can make the following comparison:
if (playerGender == Lady)
{
}
else if (playerGender == Sir)
{
}
I am currently taking a C++ programming class and am working on a project in which I have to create a fairly simple movie database. My code essentially works as intended yet in certain cases it causes the main menu to loop infinitely and I cannot figure out why. I brought this to my teacher and he cannot explain it either. He gave me a workaround but I would like to know if anyone can see the cause of the problem. Full code is as follows:
#include <cstdlib>
#include <iostream>
#include <vector>
#include <string>
using namespace std;
struct MovieType
{
string title;
string director;
int year;
int length;
string rating;
};
MovieType addMovie() {
MovieType newMovie;
cout << "Movie title :";
getline(cin, newMovie.title);
cout << "Director :";
getline(cin, newMovie.director);
cout << "Year :";
cin >> newMovie.year;
cout << "Length(in minutes) :";
cin >> newMovie.length;
cout << "Rating :";
cin >> newMovie.rating;
cout << endl;
return newMovie;
}
void listMovie(MovieType movie) {
cout << "______________________________________" << endl;
cout << "Title : " << movie.title << endl;
cout << "Director : " << movie.director << endl;
cout << "Released : " << movie.year << endl;
cout << "MPAA Rating : " << movie.rating << endl;
cout << "Running time : " << movie.length << " minutes" << endl;
cout << "______________________________________" << endl;
}
void search(vector<MovieType> movieVector) {
string strSearch;
cout << endl << "Search title: ";
getline(cin, strSearch);
for (int c = 0; c < movieVector.size(); c++) {
if (movieVector.at(c).title == strSearch)
listMovie(movieVector.at(c));
}
}
int main() {
bool quit = 0;
vector<MovieType> movieVector;
while (quit == 0) {
char selection = 'f';
cout << "Main Menu:" << endl;
cout << "'a' - Add movie" << endl;
cout << "'l' - List movies" << endl;
cout << "'s' - Search by movie title" << endl;
cout << "'q' - Quit" << endl;
cout << "Please enter one of the listed commands:";
cin >> selection;
cin.ignore();
cout << endl;
if (selection == 'a')
movieVector.push_back(addMovie());
else if (selection == 'l') {
for (int c = 0; c < movieVector.size(); c++) {
listMovie(movieVector.at(c));
}
}
else if (selection == 's') {
search(movieVector);
}
else if (selection == 'q')
quit = 1;
}
return 0;
}
When an unexpected input type is entered during the addMovie function(like entering text for the int type year), it just runs through the function then loops through the menu infinitely. It appears to me that the code just stops even looking at the input stream. I have tried using cin.ignore() in many different places but it doesn't matter if there is nothing left in the stream it just keeps going.
I am using NetBeans to compile my code.
I really have no idea why it behaves like this otherwise I would offer more information but I am just curious as to why this happens, because as I said before, my professor doesn't even know why this is happening.
Any help or insight is greatly appreciated.
cin enters an error state where cin.fail() is true. In this state it just ignores all input operations. One fix is to clear the error state, but better, only use getline operations on cin, not formatted input.
E.g., instead of
cin >> newMovie.year;
… do
newMovie.year = stoi( line_from( cin ) );
… where line_from can be defined as
auto line_from( std::istream& stream )
-> std::string
{
std::string result;
if( not getline( stream, result ) )
{
// Throw an exception or call exit(EXIT_FAILURE).0
}
return result;
}
Disclaimer: code untouched by compiler.
How can I properly use a do, while, or for loop of some kind to prevent the user from entering anything else other than the answer "1" or "2"?
If they don't, the program should tell them they cannot do that and then return them to the previous question.
#include <iostream>
#include "Options.h"
#include <string>
using namespace std;
int main(int argc, char *argv[]) {
cout << "\tWelcome to my text adventure game\n" << endl;
cout << "Please enter your characters Name: ";
string name;
cin >> name;
cout << "\nWelcome " << name << endl;
cout << "\nPlease choose the side you would like to play in - ";
Options OptionsObject;
OptionsObject.optionsSide();
string answer;
while(answer != "quit") {
cin >> answer;
cout << answer << endl;
}
if ( answer == "1" ) {
cout << "You chose the good side. Let the game begin\n " << endl;
cout << "You are located in a city named after the warrior who saved it from the evil\nmany years ago. The city of Redshore. " << endl;
cout << "You are no ordinary man in the City of Redshore. You are the king who rules it\nYou are seen as King of Justice, a good king.\nOne who only want what is best for his people" << endl;
cout << "but also a troubled man. You experienced something traumatizing when you\nwere a just a little boy, but no one knows about it,\nno one but yourself that is " << endl;
} else if( answer == "2" ) {
cout << "hey there" << endl;
}
}
Seen that this problem would be in all the choose the user will do during the game I will make an external function, to let the user choose. Maybe a static class working in this way.
int ans = Answer.getUserAnswer(2,"[1/2]>");
and this should work in this way:
public static int getUserAnswer(int max =1,string message="[1/1]>")
{
int ans = 0;
while(ans==0){
cout<<message<<" ";
cin >> answer;
if(answer>0 and answer<=max) return ans;
cout<<"\tnot a valid choose\n";
ans=0;
}
}
and you will have in your ans one of the value you expect, and it will print "not a valid choose" if the answer is not between the one you expect, and you can do this even with 10 answers, calling it by default expect you to give him just the number one.
I used it in a console game I made ;)
Hope is useful
EDIT
int getUserAnswer(int max =1,string message="[1/1]>")
{
int ans = 0;
while(ans==0){
cout<<message<<" ";
cin >> answer;
if(answer>0 and answer<=max) return ans;
cout<<"\tnot a valid choose\n";
ans=0;
}
}
and to request this code in your code:
cout << "\nWelcome " << name << endl;
cout << "\nPlease choose the side you would like to play in - ";
Options OptionsObject;
OptionsObject.optionsSide();
int answer =getUserAnswer(2,"[1/2]>");
if (answer == 1){
cout << "You chose the good side. Let the game begin\n " << endl; cout << "You are located in a city named after the warrior who saved it from the evil\nmany years ago. The city of Redshore. " << endl; cout << "You are no ordinary man in the City of Redshore. You are the king who rules it\nYou are seen as King of Justice, a good king.\nOne who only want what is best for his people" << endl; cout << "but also a troubled man. You experienced something traumatizing when you\nwere a just a little boy, but no one knows about it,\nno one but yourself that is " << endl;
}
else if(answer == 2){
cout << "hey there" << endl;
}
You should put the line where you read the input in a do loop that loops while the answer given by the user is invalid.
So, your do loop should be:
string answer;
cin >> answer;
// loop while answer is neither "1" nor "2"
while( answer != "1" && answer != "2" ) {
cout << "Please enter a 1 or a 2. You entered " << answer << endl;
cin >> answer;
}
so i made a DOS program however my game always crashes on my second time running to the cin function.
#include <iostream>
#include <string>
#include <ctime>
#include <cstdlib>
using namespace std;
//call functions
int create_enemyHP (int a);
int create_enemyAtk (int a);
int find_Enemy(int a);
int create_enemyDef (int a);
// user information
int userHP = 100;
int userAtk = 10;
int userDef = 5;
string userName;
//enemy Information
int enemyHP;
int enemyAtk;
int enemyDef;
string enemies[] = {"Raider", "Bandit", "Mugger"};
int sizeOfEnemies = sizeof(enemies) / sizeof(int);
string currentEnemy;
int chooseEnemy;
// ACTIONS
int journey;
int test;
int main()
{
// main menu
cout << "welcome brave knight, what is your name? " ;
cin >> userName;
cout << "welcome " << userName << " to Darland" << endl;
//TRAVELING
MENU:
cout << "where would you like to travel? " << endl;
cout << endl << " 1.> Theives Pass " << endl;
cout << " 2.> Humble Town " << endl;
cout << " 3.> Mission HQ " << endl;
cin >> journey;
if (journey == 1)
{
// action variable;
string c_action;
cout << "beware your journey grows dangerous " << endl;
//begins battle
// Creating the enemy, HP ATK DEF AND TYPE. ;
srand(time(0));
enemyHP = create_enemyHP(userHP);
enemyAtk = create_enemyAtk(userAtk);
enemyDef = create_enemyDef(userDef);
chooseEnemy = find_Enemy(sizeOfEnemies);
currentEnemy = enemies[chooseEnemy];
cout << " Here comes a " << currentEnemy << endl;
cout << "stats: " << endl;
cout << "HP :" << enemyHP << endl;
cout << "Attack : " << enemyAtk << endl;
cout << "Defense : " << enemyDef << endl;
ACTIONS:
cout << "Attack <A> | Defend <D> | Items <I>";
cin >> c_action;
//if ATTACK/DEFEND/ITEMS choice
if (c_action == "A" || c_action == "a"){
enemyHP = enemyHP - userAtk;
cout << " you attack the enemy reducing his health to " << enemyHP << endl;
userHP = userHP - enemyAtk;
cout << "however he lashes back causing you to have " << userHP << "health left " << endl;
//end of ATTACK ACTION
}
the last line "cin >> c_action crashes. i use two other pages. they just create the functions. is it a complier issue. also why does my complier always shutdown after it runs he app. is there a way to stop it?
A few hints:
I never use forward declarations of functions ( such as "int create_enemyHP (int a);" ) if I can avoid them. If you do this then there are two places in your code that must be correct for your program to work. It makes life easier if there is always a "single source of truth"
Have you run this code through the debugger? It will help you find problems much more quickly.
If your c_action variable is only intended to be a char, I'd suggest to use a char variable, rather than a string.
You might want to try this way, and if you're still faced with an error, you might give
scanf("%c", &c_action); //assuming you used a char.
I didn't understand if the program crashes before you type the "action" or after. Because if it crashes before, then I think your problems are caused by white spaces characters in the input buffer.