I am making a function to give the time taken to travel from Chicago to a certain city. I am trying to make it loop so that when the user chooses the city, it gives the time taken and loops back up to ask the main question and let the user choose another city. I am also including an option where they can exit the loop. What I have so far is this:
main()
{
TripInfo trip;
int choice;
do
{
cout << "You are in Chicago. Where would you like to drive?\n"
<< "Enter number of city\n" << "1. New York City\n" << "2. Boston\n"
<< "3. Philadelphia\n" << "4. Toronto\n" << "5. Washington D.C.\n"
<< "6. Miami\n" << "7. Indianapolis\n" << "8. Los Angeles\n"
<< "9. San Fransisco\n" << "10. Phoenix\n" << "11. EXIT" << endl;
cin >> choice;
if(choice = 11)
{
cout << "Program terminated." << endl;
break;
}
trip.setDistance(choice);
cout << "The distance from Chicago to " << trip.getDestination() << " is "
<< trip.getDistance() << endl;
trip.setRate();
cout << "The speed you will be travelling at from Chicago to "
<< trip.getDestination() << " is " << trip.getRate() << endl;
trip.calculateTime();
cout << "The time it will take to travel from Chicago to "
<< trip.getDestination() << " at " << trip.getRate()
<< " miles per hour will be:\n " << trip.getTime() << " hours."
<< endl;
}
}
The problem is in the output. Even though there is a condition for the if statement and if choice is not 11, the function still prints "Program terminated.". How do I fix this so that if choice = 11, the program terminates, and if choice is not 11, it continues and loops through the various functions again and again until choice is chosen to be 11?
You want choice == 11. A single = sign causes 11 to be assigned to choice (and that assignment evaluates to true).
You need to use == to compare for equality; = is assignment, returning the value assigned, and nonzero is interpreted as true.
A convention I've seen to try to prevent this issue is to put the constant on the left. The following block of code will produce a compiler error:
if(11 = choice)
{
cout << "Program terminated." << endl;
break;
}
if(choice = 11)
means you assign choice a value of 11, and test for if value is non-zero, which is true. It should be
if(choice == 11)
The correct format is
if(choice == 11) {
--- }
= is used for assignment and == is used for checking the equality.
Also you have to give a whilecondition at the end of do statement for checking the condition to enter in the loop again.
if (choice = 13) {......}
the expression is true ever, assignment expression value is var's value, above is choice, the assignment expression is 13, 13 is true.
you can write 13 = choice to protect error by compiler, but i suggest you write choice == 13 ways, because this ways will understand well.
Related
Then it will reset to the questions number 1.
I wanted to implement health points system in my code, so that if your hp goes to 0 (zero) when choosing the wrong answer, it will start to question number 1
I'm new to c++ and doesn't know much about it but if you have any recommendation how to improve my coding i'm happy to take your advice.
Code:
void questions()
{
int score, end, hp = 1;
char ans[28];
cout <<"\t\tHEALTH POINTS= " << hp <<"\n\n";
cout << "1.What thing has to be broken before it can be used?\n\n"; //Questions
cout << "[A]-Egg,";
cout << " [B]-Heart,"; //Choices
cout << " [C]-Cube,";
cout << " [D]-Case";
cout << "\n\n";
cout << "YOUR ANSWER IS: ";
cin >> ans[1];
if (ans[1]=='a'||ans[1]=='A') //This will decide if the input is correct
{
cout << "YOUR ANSWER IS CORRECT: [A] - Egg \n\n";
score++;
}
else
{
cout <<"\nWRONG! ";
cout <<"YOU NOW HAVE "<< (hp=(hp-1)) <<" HP LEFT\n\n";
}
cout << "2.Jimmy's mother had three children. The first was called April, \nthe second was called May. What was the name of the third?\n";
cout << "[A]-May,";
cout << " [B]-Jimmy,";
cout << " [C]-April,";
cout << " [D]-Third";
cout << "\n\n";
cout << "Your Answer is: ";
cin >> ans[2];
if (ans[2]=='b'||ans[2]=='B')
{
cout << "YOUR ANSWER IS CORRECT: [B] - Jimmy \n\n";
score++;
}
else
{
cout <<"\nWRONG! ";
cout <<"YOU NOW HAVE "<< (hp=(hp-1)) <<" HP LEFT\n\n";
}
cout << "\n\t\t YOUR SCORE IS:" << score << "/2, ";
cout <<"YOU HAVE "<< hp <<" HP LEFT\n\n";
cout << endl;
cout <<"\n\t\t PRESS ANY KEY TO GO BACK TO CHOICES...";
getch(); //Holds the screen
system("cls");
questions();
One way to improve your approach might be implementing some sort of function to handle asking a question, with predefined choices, and getting an answer back. Instead of writing the code out twice like you do above to ask two questions, you could call the same function twice, passing in the different arguments.
What is the best way of creating dynamic (not sure if this is the correct word) objects? For example, if I run the following:
Person man[10];
cout << "MENU" << endl;
cout << "1. Add a person to the list" << endl;
cout << "2. Delete a person from the list" << endl;
cout << "3. Change a person's information'" << endl;
cout << "4. Locate a person by ID number" << endl;
cout << "5. Locate a person by last name" << endl;
cout << "6. Print the list on the screen" << endl;
cout << "7. Load the list from a file" << endl;
cout << "8. Save the list to a file" << endl;
cout << "9. Exit the program" << endl;
cin >> a;
if (a == 1) {
if (i <= 10) {
Person man[i];
cout << "Please enter your last name: " ;
cin >> last;
man[i].setLastName(last);
i++;
cout << man[i].getLastName();
}
}
When I run this, I am allowed to enter my last name, but when I press ENTER the program stops running. What is the reason for this and is there a better way to create these objects "profiles"?
Thank you and I'm sorry if this is a stupid question.
The reason is your entire program only take one input cin >> a; and then check if its equal to 1. After the block the program has nothing left to do. So your program terminated.
If you want to edit all first name and last name of your 10 Person obj, you'd better create a loop to do that. For loop, you can google for / while.
Heres a example:
int i;
while(cin >> i)
{
if(i == 9)
return;
else if[....]
}
When you say dynamic, object allocation is via new operator. In your code, the array is already declared with 10 elements(static allocation). Hence in you code you are not performing dynamic allocation.
For dynamic allocation,add a function which can return you a new Person object. In this function create a object using new operator and return this object.
This way you add new objects dynamically.
Refer to new operator for more details on dynamic allocation.
I'm building a fairly simple contact book program to sharpen my C++ skills.
Keep in mind I didn't include all my code because this post would then be massive.
The problem I'm facing is that in the area of code shown below, contactCreator() is not actually running when it is reached in the if statement.
int mainInput;
ofstream initialStream("contacts.txt", ofstream::app);
initialStream.close();
while(mainInput != -1){
system("cls");
logoHeader();
cout << endl;
cout << "--- MAIN MENU -----------------" << endl;
cout << "[0] Create New Contact" << endl;
cout << "[1] View Existing Contacts" << endl;
cout << "[2] View or Edit Data Fields" << endl;
cout << "-------------------------------" << endl;
cout << "Press ENTER without inputting" << endl;
cout << "anything to EXIT Contact Book." << endl;
cout << "-------------------------------" << endl;
cout << "Enter Selection: ";
mainInput = menuInput();
if(mainInput == 0){
//This is the function that isn't running when it's supposed to.
contactCreator();
}else if(mainInput == 1){
contactViewer();
}else if(mainInput == 2){
dataFieldViewer();
}else if(mainInput < -1 || mainInput > 2){
invalidInputError();
}
}
return 0;
Some Information about contactCreator():
It's void, so the issue is not lack of return statements according to my limited C++ knowledge.
I checked to make sure mainInput is 0, and indeed it is.
The function is declared at the top of the program before the main function. No problem there.
I checked the spelling for the function's name. All instances are correct to my knowledge.
Can anyone see if I missed something obvious? I'm pretty new to C++, so I couldn't find any syntax error myself. All of the other functions I've created in my program run perfectly.
I tried to search the internet for my problem, but I'm a bit of a loss of how to describe it simply. Why isn't contactCreator() running as expected?
Also, here are the content of the contactCreator() function if that helps. :)
string initialName;
ofstream creatorTempStream("temp.txt");
while(initialName != ""){
system("cls");
logoHeader();
cout << endl;
cout << "--- NEW CONTACT ---------------" << endl;
cout << "Enter a name for your contact." << endl;
cout << "-------------------------------" << endl;
cout << "Press ENTER without inputting" << endl;
cout << "anything to go back." << endl;
cout << "-------------------------------" << endl;
cout << "Name: ";
getline(cin, initialName);
}
Let me know if I'm missing any relevant and important information and I'll update the post. Thanks!
If menuInput() returns the right value, the problem is most likely here (unless there is other code before the while loop):
string initialName;
ofstream creatorTempStream("temp.txt");
while(initialName != ""){
}
initialName is empty at the start of the while loop.
Did you try stepping through with a debugger? In your function contactCreator(), you are checking for initialName != "" without initializing it. The chances are that the function is running without you noticing it.
I am trying to compare two strings for a trivia program, one entered by a user and the other accessed from a node. The comparison is within an IF statement and always returns false. Below is the code used for this function. Both variables userAnswer and answer are of the type string.
cout << "Question: " << cur_ptr->question << endl;
cout << "Answer: ";
getline(cin, userAnswer);
if (userAnswer == cur_ptr->answer) {
cout << "Your answer is correct. You receive " << cur_ptr->points << " points." << endl;
totalPoints += cur_ptr->points;
}
else {
cout << "Your answer is wrong. The correct answer is: " << cur_ptr->answer << endl;
}
cout << "Your total points: " << totalPoints << endl << endl;
cur_ptr = cur_ptr->next;
Whenever my program runs, it generates an output like so
Question: How long was the shortest war on Record? (Hint: how many minutes)?
Answer: 38
Your answer is wrong. The correct answer is: 38
Your total points: 0
getline(cin, userAnswer) is keeping the \n. You might consider trimming the string with something like the following
getline(cin, userAnswer);
userAnswer.erase(userAnswer.find_last_not_of("\n\r") + 1);
No guarantees that this is the answer, but I've run across this a few times and it's just been a trailing \n or \r.
Do some boost::trim() on the strings to compare, before the comparison, and see if that helps.
Hello so my question is how do I continue on with new inputs after an else statement? In my program, I wrote an else statement that if the input is neither 1 nor 2, the user has to put a new value to get the result he/she wants. But after my else statement, my program shuts down. I don't know how to fix this. I'm very new to c++ so please keep harsh comments to yourself...
Here's my code:
// This program will allow the user to input from the keyboard
// whether the last word to the following proverb should be party or country:
// "Now is the time for all good men to come to the aid of their _______"
// Inputting a 1 will use the word party. A 2 will use the word country.
#include <iostream>
#include <string>
using namespace std;
void writeProverb(int);
int main ()
{
int wordCode;
cout << "Given the phrase:" << endl;
cout << "Now is the time for all good men to come to the aid of their ___" << endl;
cout << "Input a 1 if you want the sentence to be finished with party" << endl;
cout << "Input a 2 if you want the sentence to be finished with country." << endl;
cout << "Please input your choice now" << endl;
cin >> wordCode;
cout << endl;
writeProverb(wordCode);
return 0;
}
void writeProverb (int number)
{
if (number == 1)
cout << "Now is the time for all good men to come to the aid of their party." << endl;
else if (number == 2)
cout << "Now is the time for all good men to come to the aid of their country." << endl;
else
{
cout << "I'm sorry but that is an incorrect choice: Please input a 1 or 2" << endl;
}
}
So basically, after the else statement, I want my program to wait for the user to enter 1 or 2 instead of just shutting down.
do {
cout << "Please input your choice now" << endl;
cin >> wordCode;
cout << endl;
writeProverb(wordCode);
}while (wordCode != 1 && wordCode != 2);
This code exits if user inputs 1 or 2. Stays otherwise.
You want to have a do-while construct until you get a legal value, as Sakthi Kumar already pointed out.
However, you do not want to move the knowledge of what a legal value is up to main. Therefore, have the writeProverb method return if the value is legal or not. This keeps things in the proper abstraction level. You should also consider updating the "menu" printing by using an object, thus tying everything together.
// ... in main()
do {
cout << "Please input your choice now" << endl;
cin >> wordCode;
cout << endl;
writeProverb(wordCode);
} while( !writeProverbIfLegalNumber(wordCode) );
}
bool writeProverbIfLegalNumber (int number) {
if (number == 1) {
cout << "Now is the time for all good men to come to the aid of their party." << endl;
return true;
}
else if (number == 2) {
cout << "Now is the time for all good men to come to the aid of their country." << endl;
return true;
}
else
{
cout << "I'm sorry but that is an incorrect choice: Please input a 1 or 2" << endl;
}
return false;
}
This is basic logic, you should read about loops and how to use them. This while loop continues while wordCode is not between 1 and 2 inclusive; in other words, it continues until you get 1 or 2.
int main ()
{
int wordCode;
cout << "Given the phrase:" << endl;
cout << "Now is the time for all good men to come to the aid of their ___" << endl;
cout << "Input a 1 if you want the sentence to be finished with party" << endl;
cout << "Input a 2 if you want the sentence to be finished with country." << endl;
do
{
cout << "Please input your choice now 1 or 2: " << endl;
cin >> wordCode;
} while(!(1 <= wordCode && wordCode <=2));
cout <<endl;
writeProverb(wordCode);
return 0;
}
in this case,you can put the judging statement in the "main" function. You can use a "while" statement to control the logic.
boolean flag = true;
while(flag){
cout<<"input";
cin>>wordCode;
if(wordCode==1 || wordCode==2){
flag=false;
writeProverb(wordCode);
}
}