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)
{
}
Related
Guys I Want Help Regarding Code Below, I Want To Add A While Loop In Which A User Keeps Getting The Else Statement's Cout. Until User Satisfies If or Else-If Condition. In Other Words The Program Should Only End When User Writes 'g''G''b''B' Other Wise It Should Keep Showing The Else's Cout With Asking Again To Put The Right Value.
#include <iostream>
using namespace std;
int main()
{
string item;
float price;
int quantity;
float total;
char experience;
cout << "Write The Name Of Item You Want To Buy:" << endl;
getline(cin, item);
cout << "What Is The Price Of " << item << " In Dollars $ ?" << endl;
cin >> price;
cout << "What Is The Quantity Of " << item << endl;
cin >> quantity;
total = price*quantity;
cout << "Your Total Bill For " << quantity << " " << item << " Is " << total << "$" << endl<< endl;
cout << "How Was Your Shopping Experience Write (G) If Good And (B) For Bad" << endl;
cin >> experience;
if (experience == 'g' || experience == 'G')
{
cout << "We Appreciate Your Feedback THANKS For Shopping :)";
}
else if (experience == 'b' || experience == 'B')
{
cout << "Sorry For Bad Experience, We Will Do Better Next Time THANKS For Shopping :)";
}
else
{
cout << "Write \"G\" If Good And \"B\" If Bad";
}
Here's the answer, you should prompt for input, then check the input using a while loop instead of IF-ELSE to make sure the user provided the answer you desired. This is actually a simple logic question tho. You may explore do-while loop too.
#include <iostream>
using namespace std;
int main()
{
string item;
float price;
int quantity;
float total;
char experience;
cout << "Write The Name Of Item You Want To Buy:" << endl;
getline(cin, item);
cout << "What Is The Price Of " << item << " In Dollars $ ?" << endl;
cin >> price;
cout << "What Is The Quantity Of " << item << endl;
cin >> quantity;
total = price*quantity;
cout << "Your Total Bill For " << quantity << " " << item << " Is " << total << "$" << endl<< endl;
cout << "How Was Your Shopping Experience Write (G) If Good And (B) For Bad" << endl;
cin >> experience;
while (experience != 'G' && experience != 'g' && experience != 'B' && experience != 'b') {
cout << "Write \"G\" If Good And \"B\" If Bad\n";
cin >> experience;
}
if (experience == 'g' || experience == 'G') {
cout << "We Appreciate Your Feedback THANKS For Shopping :)";
} else if (experience == 'b' || experience == 'B') {
cout << "Sorry For Bad Experience, We Will Do Better Next Time THANKS For Shopping :)";
}
return 0;
}
Here is my code, I have attached the screenshot of what output Zybooks expects, and what my output is. I am trying to get it to output exactly what Zybooks is asking, however something seams to be wrong. It is compiling though. Or maybe Zybooks is just being stupid?
#include <iostream>
#include <string>
#include <vector>
#include <sstream>
#include <iomanip>
#include <cstring>
using namespace std;
int main() {
string title;
string col1;
string col2;
string val;
int numCommas = 0;
vector<string> stringData;
vector<int> intData;
cout << "Enter a title for the data:" << endl;
getline(cin, title);
cout << "You entered: " << title << endl << endl;
cout << "Enter the column 1 header:" << endl;
getline(cin, col1);
cout << "You entered: " << col1 << endl << endl;
cout << "Enter the column 2 header:" << endl;
getline(cin, col2);
cout << "You entered: " << col2 << endl << endl;
while (1) {
cout << "Enter a data point (-1 to stop input):" << endl;
getline(cin, val);
if (val == "-1") {
break;
}
if (val.find(',') == -1) {
cout << "Error: No comma in string." << endl << endl;
}
else {
for (int i = 0; i < val.length(); i++) {
if (val.at(i) == ',') {
numCommas++;
if (numCommas > 1){
break;
}
}
}
if (numCommas == 1) {
stringData.push_back(val.substr(0, val.find(',')));
intData.push_back(stoi(val.substr(val.find(',') + 1, val.length() - 1)));
cout << "Data string: " << val.substr(0, val.find(',')) << endl;
cout << "Data integer: " << stoi(val.substr(val.find(',') + 1, val.length() - 1)) << endl;
}
else {
cout << "Error: Too many commas in input." << endl << endl;
}
}
}
return 0;
}
Thanks.
Thanks.
Your problem is that you initialise numCommas to zero at the start of the program rather than at the start of each author input. That means, once it exceeds one, it will stay that high at least(a), meaning future inputs will always be seen as having too many commas.
You just need to set it to zero immediately before checking each input.
(a) Well, until it wraps around (if it wraps around). But that will be an awful lot of commas you need to input :-)
Not under standing looping for arrays. Looping through all of grab some or search. Can someone explain the process? Thanks in advance. Sorry if duplicate. I looked around and couldnt find a solid explaination that I could understand.
#include <fstream>
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
void allContacts(string names[], string phones[])
{
cout << "Showing all contacts... Press Q to go back to main menu" << endl;
}
void addName(string names[], string phones[])
{
bool keepGoing;
string input;
beginning:
for (int i = 0; i < sizeof(names); i++)
{
cout << "Enter contact name: ";
cin >> names[i];
cout << "Enter contact number: ";
cin >> phones[i];
cout << "Do you have another contact to add? y or no" << endl;
cin >> input;
if(input == "y" || input == "Y")
{
goto beginning;
}
if(input == "n" || input == "N")
{
cout << "Contacts you have entered: " << endl;
cout << names[i] << " : " << phones[i] << endl;
}
}
}
void searchName(string names[], string phones[])
{
string name;
cout << "Enter Name: ";
cin >> name;
cout << "Search for a name or Press Q to go back to main menu" << endl;
for (int i = 0; i < sizeof(names); i++){
if (name == names[i])
{
cout << counter << names[i] << " 's phone number is: " << phones[i] << endl;
} else {
cout << "No results found";
}
}
}
int main()
{
string names[100];
string phones[100];
int choice;
cout << "============================" << endl;
cout << "=== Welcome to PhoneBook ===" << endl;
cout << "============================" << endl;
cout << "1- Add a New Contact" << endl;
cout << "2- Search By Name" << endl;
cout << "3- Display All" << endl;
cout << "0- Exit" << endl;
cout << "Select a number: " << endl;
cin >> choice;
switch(choice)
{
case 1:
addName(names, phones);
break;
case 2:
searchName(names, phones);
break;
case 3:
allContacts(names, phones);
break;
case 0:
cout << "Exiting PhoneBook...";
break;
}
}
In C++ arrays lose attributes when passed to functions. Those attributes are capacity and size (number of filled slots). You will need to pass this additional information for each array:
void addName(string names[], unsigned int names_capacity, unsigned int names_size,
string phones[], unsigned int phones_capacity, unsigned int phones_size)
To get around this, you can use std::vector. The std::vector knows its capacity and size, so you don't have to pass additional attributes to your function.
Also, if you use tolower or toupper before you compare, you only need to make one comparison:
char input;
cout << "Do you have another contact to add? y or n" << endl;
cin >> input;
input = toupper(input);
if(input == 'Y')
When using strings, you can convert them to all uppercase or all lowercase by using std::transform, such as:
std::transform(input.begin(),
input.begin(), input.end(),
tolower);
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.
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;