Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I am supposed to make a class AddressBook containing a class called Person. My program almost, works, except when I add a person, it doesn't remember it in the next iteration of the Command menu and Display All turns up "There are 0 people in your address book." What is wrong with my code?
#include <iostream>
#include <string>
using namespace std;
class AddressBook {
public:
class Person
{
public:
char firstName[15];
char lastName[15];
char personID[15];
};
Person entries[100];
unsigned int total;
AddressBook()
{
total = 0;
}
void AddPerson()
{
cout << "This is entry number " << (total + 1) << " in your address book. " << endl;
cout << "What shall we put for the first and last name? Limit both to under 15 characters. Example: Bob Smith" << endl;
cin >> entries[total].firstName >> entries[total].lastName;
cout << "What is " << entries[total].firstName << " " << entries[total].lastName << "'s ID code?" << endl;
cin >> entries[total].personID;
++total;
cout << "..." << endl << "Successfully Added." << endl;
};
void DisplayPerson(int i)
{
cout << "Entry " << i + 1 << ": " << endl;
cout << "FIRST NAME: " << entries[i].firstName << endl;
cout << "LAST NAME: " << entries[i].lastName << endl;
cout << "ID: " << entries[i].personID << endl;
};
void DisplayEveryone()
{
cout << "You have " << total << " People in your address book." << endl;
for (int i = 0; i < total; ++i)
DisplayPerson(i);
};
void SearchPerson()
{
char lastname[32];
cout << "Please enter the last name of the person you wish to find." << endl;
cin >> lastname;
for (int i = 0; i < total; ++i)
{
if (strcmp(lastname, entries[i].lastName) == 0)
{
cout << "Person Found. " << endl;
DisplayPerson(i);
cout << endl;
}
}
};
};
int main() {
char command;
bool Exit = false;
while (Exit == false)
{
AddressBook Address_Book;
cout << "---------------COMMANDS---------------" << endl;
cout << "A: Add Person To Address Book" << endl;
cout << "S: Search for Person in Address Book" << endl;
cout << "D: Display Everyone In Address Book" << endl << endl;
cout << "Type the letter of your command: ";
cin >> command;
cout << endl;
switch (command) {
case 'A':
case 'a':
Address_Book.AddPerson();
break;
case 'S':
case 's':
Address_Book.SearchPerson();
break;
case 'D':
case 'd':
Address_Book.DisplayEveryone();
break;
default:
cout << "That is not a valid command. Closing Address Book." << endl;
cout << endl;
}
}
}
The reason is that you create a new address book in each iteration of the while loop and throw it away at the end of the iteration:
This
AddressBook Address_Book;
creates a new address book that is "thrown away" when you reach the end of its scope (ie. the end of the loop).
In reality, do you buy a new address book whenever you want to make new entry? No. You first buy the book and then (possibly in a while loop) you add entries. Move the above line outside of the loop.
Your problem is in the declaration of your address book.
Change it to the following:
AddressBook Address_Book;
while (Exit == false) {
//Ask for input and respond.
}
In your version Address_Book is declared at the start of the while loop. This means that every time an iteration of the loop completes and execution returns to the start of the block, a new local Address_Book object is created that has no knowledge of the previous objects data.
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.
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.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I'm having trouble with this do-while loop menu for a program I'm working on for school. I've checked, and as far as I'm concerned I have written the code correctly. However, when testing, if I type 'y' or 'n' the result is the same: the menu streaming down 100's of times non stop until I exit the program. Any idea on what I'm doing wrong and how I can get it to display the menu properly every time? Thanks in advance.
#include <iostream>
#include <iomanip>
#include <string>
#include "CashRegister.h"
#include "InventoryItem.h"
using namespace std;
int main()
{
// Variables
int selection, numUnits, cont;
double price;
// Use the first constructor for the first item
InventoryItem item1;
item1.setCost(5.0);
item1.setDescription("Adjustable Wrench");
item1.setUnits(10);
// Use the second constructor for the second item
InventoryItem item2("Screwdriver");
item2.setCost(3.0);
item2.setUnits(20);
// Use the third constructor for the remaining items
InventoryItem item3("Pliers", 7.0, 35);
InventoryItem item4("Ratchet", 10.0, 10);
InventoryItem item5("Socket Wrench", 15.0, 7);
do
{
cout << "#\t" << "Item\t\t\t" << "qty on Hand" << endl;
cout << "------------------------------------------------------------------" << endl;
cout << "1\t" << item1.getDescription() << "\t" << setw(3) << item1.getUnits() << endl;
cout << "2\t" << item2.getDescription() << "\t\t" << setw(3) << item2.getUnits() << endl;
cout << "3\t" << item3.getDescription() << "\t\t\t" << setw(3) << item3.getUnits() << endl;
cout << "4\t" << item4.getDescription() << "\t\t\t" << setw(3) << item4.getUnits() << endl;
cout << "5\t" << item5.getDescription() << "\t\t" << setw(3) << item5.getUnits() << endl;
cout << "Which item above is being purchased? ";
cin >> selection;
// Validate the selection
while (selection < 1 || selection > 5)
{
cout << "Error, please make a valid item selection: ";
cin >> selection;
}
cout << "How many units? ";
cin >> numUnits;
// Validate the quantity of units to make sure it isn't a negative value
while (numUnits < 0)
{
cout << "Error, please enter a valid quantity: ";
cin >> numUnits;
}
// Use a switch statement to figure out which cost to pull
switch (selection)
{
case 1: {price = item1.getCost();
item1.changeUnits(numUnits); }
break;
case 2: {price = item2.getCost();
item2.changeUnits(numUnits); }
break;
case 3: {price = item3.getCost();
item3.changeUnits(numUnits); }
break;
case 4: {price = item4.getCost();
item4.changeUnits(numUnits); }
break;
case 5: {price = item5.getCost();
item5.changeUnits(numUnits); }
break;
}
// Create a CashRegister object for this particular selection
CashRegister transaction(price, numUnits);
// Display the totals
cout << fixed << showpoint << setprecision(2);
cout << "Subtotal: $" << transaction.getSubtotal() << endl;
cout << "Sales Tax: $" << transaction.getSalesTax() << endl;
cout << "Total: $" << transaction.getPurchaseTotal() << endl;
// Find out if the user wants to purchase another item
cout << "Do you want to purchase another item? Enter y/n: ";
cin >> cont;
} while (cont != 'n' && cont != 'N');
system("pause");
return 0;
}
Your loop will never break unless you explicitly enter 110 which is the 'n' char in ASCII Codes or 78 which is the 'N'. So change your cont declaration from int cont; to char cont; and then you won't get the infinite loop anymore, and its condition will be valid to possibly break by then unless you have another hidden logical error which will require you to debug it.
Okay so as the title said its refusing to execute the stuff right under the "do" function even though as far as i can tell all the parameters for a repeat have been fulfilled. So far what i get when i run the program is something along the lines of...
"Would you like to search another name?
Please enter Y for yes and n for no:"
looping over and over when i press y
#include <iostream>
#include <string>
#include <iomanip>
#include <vector>
#include <algorithm>
#include <cstdlib>
using namespace std;
int main()
{
vector <string> vName, vID, vClass;
string sName, sID, sClass, sSearch, cQuestion;
int iSize, iStudent;
// Display initial vector size
iSize = vName.size();
cout << "Student list starts with the size:" << iSize << endl;
// Get size of list from user
cout << "How many students would you like to add?" << endl;
cin >> iStudent;
cin.ignore();
// Get names, ids, and classes
for (int i = 0; i < iStudent; i++)
{
cout << "Student" << i + 1 << ":\n";
cout << "Please enter the student name: ";
getline(cin, sName);
vName.push_back(sName);
cout << "Enter ID number ";
getline(cin, sID);
vID.push_back(sID);
cout << "Enter class name ";
getline(cin, sClass);
vClass.push_back(sClass);
}
// Display header
cout << "The list of students has the size of: " << iStudent << endl;
cout << "The Student List" << endl;
cout << "\n";
cout << "Name:" << setw(30) << "ID:" << setw(38) << "Enrolled Class : " << endl;
cout << "--------------------------------------------------------------------------";
cout << "\n";
// for loop for displying list
for (int x = 0; x < vName.size() && vID.size() && vClass.size(); x++)
{
cout << vName[x] << "\t \t \t" << vID[x] << "\t \t \t" << vClass[x] << endl;
}
// Sorting function
cout << "\n";
cout << "The Student List after Sorting:" << endl;
cout << "\n";
sort(vName.begin(), vName.end());
for (int y = 0; y < vName.size(); y++)
{
cout << vName[y] << endl;
}
cout << "\n";
// Search function
do
{
cout << "Please Enter a name to be searched:" << endl;
getline(cin, sSearch);
if (binary_search(vName.begin(), vName.end(), sSearch))
{
cout << sSearch << " was found." << endl << endl;
}
else
{
cout << sSearch << " was not found." << endl << endl;
}
cout << "Would you like to search another name?" << endl << endl;
cout << "Please enter Y for Yes and N for No:" << endl << endl;
cin >> cQuestion;
} while (cQuestion == "Y" || cQuestion == "y");
cout << "Thank you for using this program!" << endl;
return 0;
}
Edit:
Posted whole program, please excuse any grammatical mistakes, I'm just trying to get the program down before i go in there and make it pretty.
The tail of your loop does this:
cout << "Please enter Y for Yes and N for No:" << endl << endl;
cin >> cQuestion;
which will consume your string if you entered one, but leave the trailing newline in the input stream. Thus when you return to the top of the loop after entering Y or y, and do this:
cout << "Please Enter a name to be searched:" << endl;
getline(cin, sSearch);
the getline will extract an empty line.
How to consume the unread newline from the input stream is up to you. You will likely just end up using .ignore() as you did prior in your program. Or use getline to consume cQuestion. You have options. Pick one that works.
And as a side note, I would strongly advise you check your stream operations for success before assuming they "just worked". That is a hard, but necessary, habit to break. Something like this:
do
{
cout << "Please Enter a name to be searched:" << endl;
if (!getline(cin, sSearch))
break;
if (binary_search(vName.begin(), vName.end(), sSearch))
{
cout << sSearch << " was found." << endl << endl;
}
else
{
cout << sSearch << " was not found." << endl << endl;
}
cout << "Would you like to search another name?" << endl << endl;
cout << "Please enter Y for Yes and N for No:" << endl << endl;
} while (getline(cin,cQuestion) && (cQuestion == "Y" || cQuestion == "y"));
If cQuestion is a char array then you need to use strcmp or stricmp to compare it with another string i.e. "Y" and "y" in this case. If cQuestion is a single char then you need to compare with 'Y' and 'y' (i.e. with a single quote)
Strings in C++ are not first class types therefore they do not have some of the string operation that exist for other basic types like ints and floats. You do have std::string as part of the standard C++ library which almost fulfills the void.
If you just change the type of cQuestion to std::string your code should work but if you want to stick with chars then you will need to change the quote style.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I'm making a USD to MXN converter and I want to have it work both ways. The if statement works (tryed cout << "test"; and it worked) but it wont work when I replace it with the goto statement.
#include "stdafx.h"
#include <cstdlib>
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
int user;
int u, m;
cout << "US/MXN Converter" << endl;
cout << "1 US = 12.99 MXN (6/12/2014)" << endl;
cout << endl;
cout << "What Way to convert" << endl;
cout << "[1] US to MXN" << endl;
cout << "[2] MXN to US" << endl;
cout << "Selection: ";
cin >> user;
if (user == 1)
{
goto USTMXN;
}
else
{
goto MXNTUS;
}
USTMXN:
cout << "Enter the amount of US Dollars to Convert" << endl;
cout << "Amount: ";
cin >> u;
m = u * 12.99;
cout << endl;
cout << "MXN Pesos: " << m << endl;
goto END;
MXNTUS:
int mm, uu;
cout << "Enter the amount of Pesos to Convert" << endl;
cout << "Amount: ";
cin >> mm;
uu = mm / 12.99;
cout << endl;
cout << "US Dollars: " << m << endl;
goto END;
END:
system("PAUSE");
return EXIT_SUCCESS;
}
One of the most fundamental things we have to do as programmers is to learn to break problems into smaller problems. You are actually running into a whole series of problems.
I'm going to show you how to solve your problem. You may want to book mark this answer, because I'm pre-empting some problems you're going to run into a few steps down the line and preparing you - if you pay attention - to solve them on your own ;)
Let's start by stripping down your code.
Live demo here: http://ideone.com/aUCtmM
#include <iostream>
int main()
{
std::cout << "Enter a number: ";
int i;
std::cin >> i;
std::cout << "Enter a second number: ";
int j;
std::cin >> j;
std::cout << "i = '" << i << "', j = '" << j << "'\n";
}
What are we checking here? We're checking that we can ask the user two questions. That works fine.
Next is your use of goto, which I strongly recommend you do not use. It would be better to use a function. I'll demonstrate with your goto case here first:
#include <iostream>
int main()
{
int choice;
std::cout << "Enter choice 1 or 2: ";
std::cin >> choice;
if ( choice == 1 )
goto CHOSE1;
else if ( choice == 2 )
goto CHOSE2;
else {
std::cout << "It was a simple enough question!\n";
goto END;
}
CHOSE1:
std::cout << "Chose 1\n";
goto END;
CHOSE2:
std::cout << "Chose 2\n";
goto END;
END:
std::cout << "Here we are at end\n";
}
live demo: http://ideone.com/1ElcV8
So goto isn't the problem.
That leaves your use of variables. You've really mixed things up nastily by having a second set of variables (mm, uu). Not only do you not need to have these, you're doing something very naughty in that these variables only exist inside one scope and not the other. You can "get away" with this but it will come back to haunt you later on.
The difference in your two main streams of code is the variable names. The second conversion case looks like this:
MXNTUS:
int mm, uu;
cout << "Enter the amount of Pesos to Convert" << endl;
cout << "Amount: ";
cin >> mm;
uu = mm / 12.99;
cout << endl;
cout << "US Dollars: " << m << endl;
goto END;
The problem here is that you have - accidentally - used the variable "m" in your output. It's what we call uninitialized.
cout << "US Dollars: " << m << endl;
That m in the middle should be mm.
Your compiler should actually be warning you about this. If it's not, and you're just setting out learning, you should figure out how to increase the compiler warning level.
It would be better to make a function to do the conversions; you could make one function for each direction, but I've made a function that handles both cases:
#include <iostream>
static const double US_TO_MXN = 12.99;
static const char DATA_DATE[] = "6/12/2014";
void convert(const char* from, const char* to, double exchange)
{
std::cout << "Enter the number of " << from << " to convert to " << to << ".\n"
"Amount: ";
int original;
std::cin >> original;
std::cout << to << ": " << (original * exchange) << '\n';
}
int main() // this is valid since C++2003
{
std::cout << "US/MXN Converter\n"
"1 US = " << US_TO_MXN << " MXN (" << DATA_DATE << ")\n"
"\n";
int choice = 0;
// Here's a better demonstration of goto
GET_CHOICE:
std::cout << "Which conversion do you want to perform?\n"
"[1] US to MXN\n"
"[2] MXN to US\n"
"Selection: ";
std::cin >> choice;
if (choice == 1)
convert("US Dollars", "Pesos", US_TO_MXN);
else if (choice == 2)
convert("Pesos", "US Dollars", 1 / US_TO_MXN);
else {
std::cerr << "Invalid choice. Please try again.\n";
goto GET_CHOICE;
}
// this also serves to demonstrate that goto is bad because
// it's not obvious from the above that you have a loop.
}
ideone live demo: http://ideone.com/qwpRtQ
With this, we could go on to clean things up a whole bunch and extend it:
#include <iostream>
using std::cin;
using std::cout;
static const double USD_TO_MXN = 12.99;
static const double GBP_TO_MXN = 22.03;
static const char DATA_DATE[] = "6/12/2014";
void convert(const char* from, const char* to, double exchange)
{
cout << "Enter the number of " << from << " to convert to " << to << ".\n"
"Amount: ";
int original;
cin >> original;
cout << '\n' << original << ' ' << from << " gives " << int(original * exchange) << ' ' << to << ".\n";
}
int main() // this is valid since C++2003
{
cout << "Foreign Currency Converter\n"
"1 USD = " << USD_TO_MXN << " MXN (" << DATA_DATE << ")\n"
"1 GBP = " << GBP_TO_MXN << " MXN (" << DATA_DATE << ")\n"
"\n";
for ( ; ; ) { // continuous loop
cout << "Which conversion do you want to perform?\n"
"[1] USD to MXN\n"
"[2] MXN to USD\n"
"[3] GBP to MXN\n"
"[4] MXN to GBP\n"
"[0] Quit\n"
"Selection: ";
int choice = -1;
cin >> choice;
cout << '\n';
switch (choice) {
case 0:
return 0; // return from main
case 1:
convert("US Dollars", "Pesos", USD_TO_MXN);
break;
case 2:
convert("Pesos", "US Dollars", 1 / USD_TO_MXN);
break;
case 3:
convert("British Pounds", "Pesos", GBP_TO_MXN);
break;
case 4:
convert("Pesos", "British Pounds", 1 / GBP_TO_MXN);
break;
default:
cout << "Invalid selection. Try again.\n";
}
}
}
http://ideone.com/iCXrpU
There is a lot more room for improvement with this, but I hope it helps you on your way.
---- EDIT ----
A late tip: It appears you're using visual studio, based on the system("PAUSE"). Instead of having to add to your code, just use Debug -> Start Without Debugging or press Ctrl-F5. It'll do the pause for you automatically :)
---- EDIT 2 ----
Some "how did you do that" points.
cout << '\n' << original << ' ' << from << " gives " << int(original * exchange) << ' ' << to << ".\n";
I very carefully didn't do the using namespace std;, when you start using more C++ that directive will become the bane of your existence. It's best not to get used to it, and only let yourself start using it later on when you're a lot more comfortable with C++ programming and more importantly debugging odd compile errors.
But by adding using std::cout and using std::cin I saved myself a lot of typing without creating a minefield of function/variable names that I have to avoid.,
What does the line do then:
cout << '\n' << original << ' ' << from << " gives " << int(original * exchange) << ' ' << to << ".\n";
The '\n' is a single character, a carriage return. It's more efficient to do this than std::endl because std::endl has to go poke the output system and force a write; it's not just the end-of-line character, it actually terminates the line, if you will.
int(original * exchange)
This is a C++ feature that confuses C programmers. I'm actually creating a "temporary" integer with the result of original * exchange as parameters.
int i = 0;
int i(0);
both are equivalent, and some programmers suggest it is better to get into the habit of using the second mechanism so that you understand what happens when you later run into something called the "most vexing parse" :)
convert("Pesos", "British Pounds", 1 / GBP_TO_MXN)
The 1 / x "invert"s the value.
cout << "Foreign Currency Converter\n"
"1 USD = " << USD_TO_MXN << " MXN (" << DATA_DATE << ")\n"
"1 GBP = " << GBP_TO_MXN << " MXN (" << DATA_DATE << ")\n"
"\n";
This is likely to be confusing. I'm mixing metaphors with this and I'm a little ashamed of it, but it reads nicely. Again, employ the concept of breaking problems up into smaller problems.
cout << "Hello " "world" << '\n';
(note: "\n" and '\n' are different: "\n" is actually a string whereas '\n' is literally just the carriage return character)
This would print
Hello world
When C++ sees two string literals separated by whitespace (or comments) like this, it concatenates them, so it actually passes "Hello world" to cout.
So you could rewrite this chunk of code as
cout << "Foreign Currency Converter\n1 USD = ";
cout << USD_TO_MXN;
cout << " MXN (";
cout << DATA_DATE;
cout << ")\n1 GBP = ";
cout << GBP_TO_MXN;
cout << " MXN (";
cout << DATA_DATE;
cout << ")\n\n";
The << is what we call "semantic sugar". When you write
cout << i;
the compiler is translating this into
cout.operator<<(i);
This odd-looking function call returns cout. So when you write
cout << i << j;
it's actually translating it to
(cout.operator<<(i)).operator<<(j);
the expression in parenthesis (cout.operator<<(i)) returns cout, so it becomes
cout.operator<<(i); // get cout back to use on next line
cout.operator<<(j);
Main's fingerprint
int main()
int main(int argc, const char* argv[])
Both are legal. The first is perfectly acceptable C or C++. The second is only useful when you plan to capture "command line arguments".
Lastly, in main
return 0;
Remember that main is specified as returning int. The C and C++ standards make a special case for main that say its the only function where it's not an error not to return anything, in which case the program's "exit code" could be anything.
Usually its best to return something. In C and C++ "0" is considered "false" while anything else (anything that is not-zero) is "true". So C and C++ programs have a convention of returning an error code of 0 (false, no error) to indicate the program was successful or exited without problems, or anything else to indicate (e.g. 1, 2 ... 255) as an error.
Using a "return" from main will end the program.
Try to change youre code for sth like this. Using goto label is not recommended.
Main idea of switch statement :
int option;
cin >> option
switch(option)
{
case 1: // executed if option == 1
{
... code to be executed ...
break;
}
case 99: //executed id option == 99
{
... code to be executed
break;
}
default: // if non of above value was passed to option
{
// ...code...
break;
}
}
Its only example.
int main(int argc, char *argv[])
{
int user;
int u, m;
cout << "US/MXN Converter" << endl;
cout << "1 US = 12.99 MXN (6/12/2014)" << endl;
cout << endl;
cout << "What Way to convert" << endl;
cout << "[1] US to MXN" << endl;
cout << "[2] MXN to US" << endl;
cout << "Selection: ";
cin >> user;
switch(user )
{
case 1 :
{
//USTMXN:
cout << "Enter the amount of US Dollars to Convert" << endl;
cout << "Amount: ";
cin >> u;
m = u * 12.99;
cout << endl;
cout << "MXN Pesos: " << m << endl;
break;
}
}
default :
{
//MXNTUS:
int mm, uu;
cout << "Enter the amount of Pesos to Convert" << endl;
cout << "Amount: ";
cin >> mm;
uu = mm / 12.99;
cout << endl;
cout << "US Dollars: " << m << endl;
break;
}
}
system("PAUSE");
return EXIT_SUCCESS;
}