Modularization in C++ - c++

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.

Related

Program not saving inputted entries? (C++) [closed]

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.

C++ assignment help on creating codes for reusability?

I've been having trouble doing this assignment. I'm just having a hard time understanding and I am not entirely sure what to do. I've researched and watched videos and havent been able to find the right, specific information. Its a bunch of questions, so I hope someone can not only giveme the answers, but also explain to me so I have a strong understanding :) . Here are the questions:
1)In this exercise we have been given some program code that will accept two integers as inputs
and evaluate which one holds the larger value. This evaluation occurs in multiple places
throughout the code. Write a function that the program could use to perform this same evaluation
instead of duplicating the code over and over. Start by writing a suitable function declaration
towards the beginning of the code file. You will have to decide whether your function will return
some output or not.
2) With your declaration written proceed to define the function, including the appropriate pieces of
code that will evaluate which of the two integers is the largest. If you stated earlier that your
function will return a value, be sure to define what it will return here.
3) Use your result from parts (1) and (2) to reduce the amount of duplicate code in the main function
provided by replacing the multiple instances of the integer comparison with a call to invoke the
function you have created. Remember that the function will require two integers to be passed in
as arguments and if you are returning some value from the function it should be used (stored in
a variable, outputted to screen, etc.). As a word of advice, test your function works correctly after
replacing just one of the evaluations, don’t replace them all at once (if the function works correctly
for the first replacement then it should work for the others).
4) Since the function you have created only compares the values of its parameters and doesn’t write
to them (i.e. change the value stored in them) we should specify in the function declaration and
definition that these parameters should be treated like constants. Make the necessary
modifications to the function and test again to verify the function still works. Confirm the function
will not let you change the data of the parameters by trying to include an operation in the function
that would change the value of one of the variables (e.g. number2 += 10;)
-- Here is the code ( I apologise for the long writing):
#include <iostream>
int main(void)
{
using std::cout;
using std::cin;
using std::endl;
int nNum1 = 10, nNum2 = 11;
cout << "This program will compare two numbers and report which one is larger.\n\n"
<< "Proceeding with evaluation...\n" << endl;
cout << "\nUsing numbers: " << nNum1 << " and " << nNum2 << ", the larger one is: ";
if (nNum1 > nNum2)
cout << nNum1 << endl;
else if (nNum1 < nNum2)
cout << nNum2 << endl;
else
cout << "Neither of them! It's a draw." << endl;
int numberA = 234;
int numberB = 234;
cout << "\nUsing numbers: " << numberA << " and " << numberB << ", the larger one is: ";
if (numberA > numberB)
cout << numberA << endl;
else if (numberA < numberB)
cout << numberB << endl;
else
cout << "Neither of them! It's a draw." << endl;
int one = 'a';
int two = 'A';
cout << "\nUsing numbers: " << one << " and " << two << ", the larger one is: ";
if (one > two)
cout << one << endl;
else if (one < two)
cout << two << endl;
else
cout << "Neither of them! It's a draw." << endl;
cout << "\nUsing numbers: " << 13 << " and " << 84 << ", the larger one is: ";
if (13 > 84)
cout << 13 << endl;
else if (13 < 84)
cout << 84 << endl;
else
cout << "Neither of them! It's a draw." << endl;
int input1 = 0;
int input2 = 0;
cout << "\nPlease enter a number: ";
cin >> input1;
cout << "\nPlease enter a second number: ";
cin >> input2;
cout << "\nUsing numbers: " << input1 << " and " << input2 << ", the larger one is: ";
if (input1 > input2)
cout << input1 << endl;
else if (input1 < input2)
cout << input2 << endl;
else
cout << "Neither of them! It's a draw." << endl;
cout << "\n\tThank you for running me :3\n" << endl;
return 0;
}
You basically have to refactor the code to replace the duplicate code part in your main function.
If you look closely you will see that code like this repeats:
cout << "\nUsing numbers: " << nNum1 << " and " << nNum2 << ", the larger one is: ";
if (nNum1 > nNum2)
cout << nNum1 << endl;
else if (nNum1 < nNum2)
cout << nNum2 << endl;
else
cout << "Neither of them! It's a draw." << endl;
So put that into a function:
void CompareNumbers(int nNum1, int nNum2)
{
cout << "\nUsing numbers: " << nNum1 << " and " << nNum2 << ", the larger one is: ";
if (nNum1 > nNum2)
cout << nNum1 << endl;
else if (nNum1 < nNum2)
cout << nNum2 << endl;
else
cout << "Neither of them! It's a draw." << endl;
}
And call this in your main function instead of duplicating the said code block.

I am trying to use a do while loop to repeat a certain portion of my program and it refuses to execute properly

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.

(C++) Goto statement not working. Beginner [closed]

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;
}

program crashes at CIN input | C++

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.