Hi I'm new with c++ and am having a hard time with creating a code to convert currencies. Could you please look at my current code and give any suggestions. the first goal is first to determine the type of currency. then the amount. finally the conversion.
#include <iostream>
#include <string>
using namespace std;
int main()
{
//declaring constant conversion values of currency per dollar
const float ColombianPeso = 2000;
const float MexicanPeso = 13.25;
const float ArgentinePeso = 8.4;
const float VenesuelanBolivar = 6.28;
const float ChileanPeso = 593.719;
//designing statement to allow user to input curency type
char currency[] = "show me the money (USDollar, MexicanPeso, ArgentinePeso, ColombianPeso, VenesuelanBolivar, or ChileanPeso):\n";
char answer1[17];
cout << currency;
cin >> answer1;
//designing statement to imput amount
float amount = 0;
cout << "enter amount:\n";
cin >> amount;
//creating if/else statement to convert for diffent money values
if (answer1 == USDollar)
cout << "number of Colombian Pesos:\n" << amount * ColombianPeso;
cout << "number of Venesuelan Bolivars:\n" << amount * VenesuelanBolivar;
cout << "number of Mexican Pesos:\n" << amount * MexicanPeso;
cout << "number of Argentine Pesos:\n" << amount * ArgentinePeso;
cout << "number of Chilean Pesos:\n" << amount * ChileanPeso;
else if (answer1 == MexicanPeso)
cout << "number of US Dollars:\n" << amount / MexicanPeso;
else if (answer1 == ColombianPeso)
cout << "number of US Dollars:\n" << amount / ColombianPeso;
else if (answer1 == ArgentinePeso)
cout << "number of US Dollars:\n" << amount / ArgentinePeso;
else if (answer1 == ChileanPeso)
cout << "number of US Dollars:\n" << amount / ChileanPeso;
else if (answer1 == VenesuelanBolivar)
cout << "number of US Dollars:\n" << amount / VenesuelanBolivar;
else
cout << "try again with VenesuelanBolivar, USDollar, ChileanPeso, ArgentinePeso, ColombianPeso, or MexicanPeso:\n";
return 0;
}
Use a std::string instead of char[]. Also you need to compare to string literals, otherwise it will think those are variables.
std::string answer1;
cin >> answer1;
if (answer1 == "USDollar")
{
// do stuff
}
You're comparing char[] and float, I think you don't want it.
const float ColombianPeso = 2000;
//...
char answer1[17];
//...
cin >> answer1;
//...
else if (answer1 == ColombianPeso)
I'd recommend you to use std::unordered_map; it allows you to in example get float used to conversion when you give a string. Also, it allows modify currency and their ratio in runtime.
#include <string>
#include <unordered_map>
#include <iostream>
#include <stdexcept>
using std::cout;
using std::cin;
using std::clog;
int main(){
std::unordered_map<std::string, float> ratio{
{"ColombianPeso", 2000},
{"MexicanPeso", 13.45},
{"ArgentinePeso", 8.4},
{"VenesueleanBolivar", 6.28},
{"ChileanPeso", 593.719}
};
clog << "Available currency:\n";
for(auto it=ratio.cbegin(); it!=ratio.cend(); ++i)
clog<< '\t' << it->first << ' ' << it->second << '\n';
clog << "Pick one of currency above: ";
std::string choice;
cin >> choice;
try{
auto value=ratio.at(choice); /*if element doesn't exist,
program jumps to the catch*/
float amount;
clog >> "Enter amount: ";
cin >> amount;
cout << value*amount << '\n';
}catch(std::out_of_range&){
clog << "Given currency is not available.\n";
}
}
Related
I must write a program where the user can choose to practice with topic addition or topic multiplication that starts with a self-driven menu.
It must keep track of questions answered right, wrong and the number of questioned asked.
Which my current program is doing within each module(topic). Example Addition keeps track of the questions while the user is practicing Addition only and Multiplication does the same.
However, they are not being feedback to main, so they are not being added or displayed before the user can select another topic to practice or to exit the program.
Currently it is only to keeping track of the question (right /wrong/ total of questions) for each module (topic).
My goal is for the values to be passed to main and display the total number (right /wrong/ total of questions) before the user exits the program, but at the same time I must display the number of question in the Additional Topic and the Multiplication topic and provide a total.
Example Table of Addition, Multiplication and Totals ?
This is the code I have to start with. Can someone help me in how to code to return values of the (right /wrong/ total of questions) of the two topics and accomplish to display something like the table information.
******************************************************************************* /
#include <stdio.h> /* printf, scanf, puts, NULL */
#include <stdlib.h> /* srand, rand */
#include <time.h> /* time */
#include <string> // String managment funtions.
#include <iostream> // For input and output
#include <cmath> // For math functions.
#include <math.h>
#include <cstdlib>
using namespace std;
////////////////////////////////////////////////////////////////////////
// Implementing menu driven programs.
// Function Prototypes.
int menu();
void sums();
void products();
int main()
{
srand(time(0));
int option;
do {
option = menu();
switch (option) {
case 1: {
sums();
break;
}
case 2: {
products();
break;
}
default:
cout << "Program exit" << endl;
}
} while (option != 6);
return 0;
}
int menu()
{
cout << "Please select an option" << endl;
cout << "1) Practice with Addition " << endl;
cout << "2) Pratice with Multiplication " << endl;
cout << "3) Exit the program " << endl;
int option;
cin >> option;
return option;
}
void sums()
{
string keepgoing;
unsigned int quantity_total_questions = 0U;
unsigned int quantity_wrong_answers = 0U;
unsigned int quantity_correct_answers = 0U;
do {
const int minValue = 10;
const int maxValue = 99;
int y = (rand() % (maxValue - minValue + 1)) + minValue;
// cout<< " the random number is y "<< y << endl;
int x = (rand() % (maxValue - minValue + 1)) + minValue;
// cout<< " the random number is x "<< x << endl;
cout << "What is " << x << " + " << y << " =" << endl;
int answer;
cin >> answer;
if (answer == (x + y)) {
cout << "Great!! You are really smart!!" << endl;
++quantity_correct_answers;
++quantity_total_questions;
}
else {
cout << "Oh Sorry Try Again." << endl;
++quantity_wrong_answers;
++quantity_total_questions;
}
cout << "Right: " << quantity_correct_answers;
cout << " Wrong: " << quantity_wrong_answers;
cout << " Total Questions: " << quantity_total_questions << endl;
cout << "Do you want to play again? [enter y for yes or n for no]" << endl;
cin >> keepgoing;
} while (keepgoing == "y");
}
void products()
{
{
string keepgoing;
unsigned int quantity_total_questions = 0U;
unsigned int quantity_wrong_answers = 0U;
unsigned int quantity_correct_answers = 0U;
do {
const int minValueOne = 0;
const int maxValueOne = 9;
const int minValueTwo = 10;
const int maxValueTwo = 99;
int y = (rand() % (maxValueOne - minValueOne + 1)) + minValueOne;
// cout<< " the random number is y "<< y << endl;
int x = (rand() % (maxValueTwo - minValueTwo + 1)) + minValueTwo;
// cout<< " the random number is x "<< x << endl;
cout << " What is " << x << " x " << y << " =" << endl;
int answer;
cin >> answer;
if (answer == (x * y)) {
cout << "Great!! You are really smart!!" << endl;
++quantity_correct_answers;
++quantity_total_questions;
}
else {
cout << "Oh Sorry Try Again." << endl;
++quantity_wrong_answers;
++quantity_total_questions;
}
cout << "Right: " << quantity_correct_answers;
cout << " Wrong: " << quantity_wrong_answers;
cout << " Total Questions: " << quantity_total_questions << endl;
cout << "Do you want to play again? [enter y for yes or n for no]" << endl;
cin >> keepgoing;
} while (keepgoing == "y");
}
}
I would create a structure that contains the number of total answers and number of correct answers—the incorrect ones can be inferred—and then pass a reference to an instance of the structure to the respective sums() and products() functions.
Those functions can then populate the structure elements and when they return, your main function can read them out, knowing exactly how many questions were asked, how many were answered, or whatever other information you want to record and retrieve.
I do not understand why these errors exist about the operands. I also am curious, when I print out "Your bill is...", how do I allow the computer to calculate the bill for me?
Your error is because you are trying to compare an int to a string, which won't work, that comparison is not defined. Besides, your string is empty anyway.
Also, your if has an erroneous ; on the end of it. In fact, your whole if makes no sense and should be removed.
Try this instead:
#inslude <iostream>
using namespace std;
int main()
{
int TDU, kWh;
cout << "Who is your TDU?\n";
cin >> TDU;
cout << "How many kWh did you use for the month you would like to calculate?\n";
cin >> kWh;
cout << "Your bill is " << 3.42 + (0.0384470 * kWh);
return 0;
}
UPDATE: That being said, you probably meant to do something more like this instead:
#inslude <iostream>
using namespace std;
static const int ONCOR = ...; // <-- for you to fill in as needed...
int main()
{
int TDU, kWh;
cout << "Who is your TDU?\n";
cin >> TDU;
cout << "How many kWh did you use for the month you would like to calculate?\n";
cin >> kWh;
if (TDU == ONCOR)
cout << "Your bill is " << 3.42 + (0.0384470 * kWh);
return 0;
}
Alternatively:
#inslude <iostream>
using namespace std;
int main()
{
string TDU;
int kWh;
cout << "Who is your TDU?\n";
cin >> TDU;
cout << "How many kWh did you use for the month you would like to calculate?\n";
cin >> kWh;
if (TDU == "ONCOR")
cout << "Your bill is " << 3.42 + (0.0384470 * kWh);
return 0;
}
Depending on what format you want the user to enter the TDU as.
When I run the program with either one or more customers. It seems to be that Only with the first customer data, the code I have does not do the calculations correctly for the first customer when trying to get the monthly payments and interest but the calculations are done correctly for the rest of the customers data inputted. What am I missing? Thank you.
#include <iostream>
#include <string>
#include <cmath>
#include <iomanip>
#include <vector>
using namespace std;
int main()
{
//Variables
vector <double> Loanlgth, Loanamt, interestRate;
vector <double> monthlyPay(100), loanTotal(100), creditScore(100), totalInterest;
char yes;
const int INPUT_CUSTOMER = 1, DISPLAY_LOAN = 2, EXIT_PROGRAM = 3;
vector <string> customerName;
int option;
int numCustomers = 0;
int index = 0;
//Program
cout << "Thank you for choosing The Bank of UA for your loan requirements!\n\n";
do
{
cout << "UA Bank menu:\n\n"
<< "1. Enter your information\n"
<< "2. See your loan requirements\n"
<< "3. Exit program\n\n"
<< "Choose an option: ";
cin >> option;
while (option < INPUT_CUSTOMER || option > EXIT_PROGRAM)
{
cout << "Please enter a valid menu option: ";
cin >> option;
}
if (option == 1) //Customer enters their information
{
cout << "Please enter the number of customers you would like\n"
<< " to enter loan information for: ";
cin >> numCustomers;
for (index = 0; index < numCustomers; index++)
{
string tempName;
double tempLoanamt, tempLoanlgth, tempcreditScore, tempinterestRate, tempinterest;
cout << "Please enter your name: ";
cin >> tempName;
customerName.push_back(tempName);
cout << "Please enter the loan amount: $";
cin >> tempLoanamt;
Loanamt.push_back(tempLoanamt);
cout << "Please enter the length of the loan in months: ";
cin >> tempLoanlgth;
Loanlgth.push_back(tempLoanlgth);
cout << "What is your current credit score? ";
cin >> tempcreditScore;
creditScore.push_back(tempcreditScore);
if (tempcreditScore <= 600)
tempinterestRate = .12;
interestRate.push_back(tempinterestRate);
if (tempcreditScore > 600)
tempinterestRate = .05;
interestRate.push_back(tempinterestRate);
//Calculations
tempinterest = Loanamt[index] * interestRate[index];
totalInterest.push_back(tempinterest);
loanTotal[index] = (Loanamt[index] + totalInterest[index]);
monthlyPay[index] = loanTotal[index] / Loanlgth[index];
}
}
if (option == 2) // Displays monthly payment
{
cout << fixed << setprecision(2);
for (index = 0; index < numCustomers; index++)
cout << customerName[index] << " your total loan is " << loanTotal[index] << "\n"
<< "with a monthly payment of $" << monthlyPay[index] << "\n"
<< "for " << Loanlgth[index] << " months with an interest\n"
<< "rate of " << interestRate[index] << endl;
}
} while (option != EXIT_PROGRAM);
system("pause");
return 0;
}
Currently, interestRate is populated wrongly. Initially, it contains a garbage value because it is not initialized and if the first condition is not true, the garbage value is pushed, otherwise .12. Next, if the second condition is true, .05 is pushed, otherwise the values from the above flow. So, these combinations of garbage and assigned values are causing values to be pushed twice.
Here's your code:
if (tempcreditScore <= 600)
tempinterestRate = .12;
interestRate.push_back(tempinterestRate);
if (tempcreditScore > 600)
tempinterestRate = .05;
interestRate.push_back(tempinterestRate);
You can correct this in a number of ways:
// push after the calculation is complete
if (tempcreditScore <= 600)
tempinterestRate = .12;
if (tempcreditScore > 600)
tempinterestRate = .05;
interestRate.push_back(tempinterestRate);
or, with if-else (preferable):
if (tempcreditScore <= 600)
tempinterestRate = .12;
else
tempinterestRate = .05;
interestRate.push_back(tempinterestRate);
or, with ternary operator ?: (conciseness and you can make it const):
const double tempinterestRate = (tempcreditScore <= 600 ? .12 : .05);
interestRate.push_back(tempinterestRate);
Apart from this, there are a number of points:
The naming convention is inconsistent throughout the code.
The variables must be initialized because the uninitialized ones may lead to Undefined Behavior.
In the absence of an aggregate type such as struct or class and with multiple pieces of information to store separately in vectors, it is better to keep all the push_backs exactly to once per iteration.
Magic numbers can be avoided for 600, .12 and .5.
The magic numbers for option comparison in if conditions can be removed with their proper constant equivalents i.e. INPUT_CUSTOMER and DISPLAY_LOAN. And, if-else can be used instead of if-if.
The scoping could be improved by moving the variables and objects closer to where they are used.
The vertical blank spaces can improve readability for relevant code blocks.
And, Why is "using namespace std;" considered bad practice?
There might be some other points that you can observe in the following updated code (live):
#include <iostream>
#include <string>
#include <iomanip>
#include <vector>
int main()
{
// Variables
std::vector<std::string> customerNames;
std::vector<double> loanLengths, loanAmounts, interestRates;
std::vector<double> monthlyPays, loanTotals, creditScores, totalInterests;
// Program
std::cout << "Thank you for choosing The Bank of UA for your loan requirements!\n\n";
const int INPUT_CUSTOMER = 1, DISPLAY_LOAN = 2, EXIT_PROGRAM = 3;
int option = EXIT_PROGRAM;
do
{
std::cout << "UA Bank menu:\n\n"
<< "1. Enter your information\n"
<< "2. See your loan requirements\n"
<< "3. Exit program\n\n"
<< "Choose an option: ";
std::cin >> option;
while (option < INPUT_CUSTOMER || option > EXIT_PROGRAM)
{
std::cout << "Please enter a valid menu option: ";
std::cin >> option;
}
if (option == INPUT_CUSTOMER) //Customer enters their information
{
int numCustomers = 0;
std::cout << "Please enter the number of customers you would like\n"
<< " to enter loan information for: ";
std::cin >> numCustomers;
for ( int index = 0; index < numCustomers; index++ )
{
std::string name;
double loanAmount = 0.0, loanLength = 0.0, creditScore = 0.0;
std::cout << "Please enter your name: ";
std::cin >> name;
customerNames.push_back( name );
std::cout << "Please enter the loan amount: $";
std::cin >> loanAmount;
loanAmounts.push_back( loanAmount );
std::cout << "Please enter the length of the loan in months: ";
std::cin >> loanLength;
loanLengths.push_back( loanLength );
std::cout << "What is your current credit score? ";
std::cin >> creditScore;
creditScores.push_back( creditScore );
double interestRate = 0.0;
if (creditScore <= 600)
interestRate = .12;
else
interestRate = .05;
// Ternary operator (?:) may also be used here
// const double interestRate = creditScore <= 600 ? .12 : .05;
interestRates.push_back(interestRate);
//Calculations
const double tempTotalInterest = loanAmounts[index] * interestRates[index];
totalInterests.push_back( tempTotalInterest );
const double tempTotalLoan = loanAmounts[index] + totalInterests[index];
loanTotals.push_back( tempTotalLoan );
const double tempMonthlyPay = loanTotals[index] / loanLengths[index];
monthlyPays.push_back( tempMonthlyPay );
}
}
else if (option == DISPLAY_LOAN) // Displays monthly payment
{
std::cout << std::fixed << std::setprecision(2);
for (int index = 0; index < customerNames.size(); index++)
{
std::cout << "\n---\n";
std::cout << customerNames[index] << " your total loan is " << loanTotals[index]
<< "\nwith a monthly payment of $" << monthlyPays[index]
<< "\nfor " << loanLengths[index] << " months with an interest"
<< "\nrate of " << interestRates[index] << std::endl;
std::cout << "---\n";
}
}
} while (option != EXIT_PROGRAM);
return 0;
}
I am getting this error every time I try to run my program.
This application has requested the Runtime to terminate it in an unusual way.
Please contact the application's support team for more information.
terminate called after throwing an instance of
'std::logic_error' what(): basic_string::_M_construct null not valid
#include <iostream>
#include <string>
using namespace std;
struct Bin
{
string desc;
int partsQty;
};
void addParts(Bin bList[], int i);
void removeParts(Bin bList[], int i);
int main() {
char response;
int binNumber;
const int NUM_OF_BINS = 11;
Bin binList[NUM_OF_BINS] = {
{0,0},
{"Valve", 10},
{"Earing",5},
{"Bushing",15},
{"Coupling",21},
{"Flange",7},
{"Gear",5},
{"Gear Housing",5},
{"Vaccum Gripper",25},
{"Cable",18},
{"Rod",12}
};
for(int i=1;i < 11;i++)
{
cout << "Bin #" << i << " Part: " << binList[i].desc << " Quantity " << binList[i].partsQty << endl;
}
cout << "Please select a bin or enter 0 to terminate";
cin >> binNumber;
cout << "Would you like to add or remove parts from a certain bin?(A or R)";
cin >> response;
if(response == 'a')
addParts(binList, binNumber);
else if(response == 'r')
removeParts(binList, binNumber);
return 0;
}
void addParts(Bin bList[], int i)
{
int parts;
int num;
cout << "How many parts would you like to add?";
cin >> num;
parts = bList[i].partsQty + num;
cout << "Bin # " << i << " now contains " << parts << " parts";
}
void removeParts(Bin bList[], int i)
{
int parts;
int number;
cout << "Which bin would you like to remove parts to?";
cin >> i;
cout << "How many parts would you like to remove?" << endl;
cin >> number;
parts = bList[i].partsQty - number;
if(parts < 0)
cout << "Please enter a number that isn't going to make the amount of parts in the bin negative.";
cin >> number;
parts = bList[i].partsQty - number;
cout << "The remaining amount of parts in bin #" << i << " is " << parts;
}
It comes from:
{0,0}
in your list of initializers for binList. 0 is not a correct initializer for std::string. You could perhaps use {"", 0} instead, or even {}.
Another idea might be to revise your program logic so that you do not require a dummy entry at the start of the array.
I have created an solution that compiles correctly, but when I enter in the required input it provides only a value of '0' which is not correct. It started when I amended the code to have exception handling but for some reason now, the code no longer processes. The first three input values can be anything and it will still output '0' when run. Thoughts?
#include <iostream>
#include <cmath>
#include <string>
#include <sstream>
#include <stdexcept>
using namespace std;
class MortgageCalc
{
private:
double loan, interest;
int years;
public:
MortgageCalc() = default;
void setLoan(double l) { loan = l; } //mutator
void setIntrest(double i) { interest = i; } //mutator
void setYears(short y) { years = y; } //mutator
double getMonthlyDue(double term) { return ((loan * ((interest / 100) / 12) * term) / (term - 1)); } //constructor to run math calculation on montly loan amou
double getTotalDue(double term) { return (getMonthlyDue(term) * (years * 12)); } //constructor to compute total amount with interest
double getTotalInt(double term) { return (getTotalDue(term) - loan); }
};
int main()
{
MortgageCalc mort1;
int choice = 0;
int years = 0;
double term(0), loan(0), interest(0);
cout << "Enter the total loan amount on your mortgage loan: $"; //established loan variable
{
std::string loan;
try
{
cin >> loan;
}
catch (string loan) //Exception for comma in 'loan' input by user
{
if (loan.find_first_not_of("0123456789.") != std::string::npos) // npos invalid pseudo-index
{
std::cerr << "bad input, must use whole numbers only\n" << endl;
return 1;
}
std::istringstream ins(loan); // Converts the string into a number without punctuation
ins >> loan;
}
}
// cout << "Loan amount cannot be negative. Enter the amount: ";
mort1.setLoan(loan);
cout << "Enter the interest rate (in whole #'s only): "; //establishes interest rate variable
cin >> interest; {
if (interest <= 0) { //example if you put 0 or negative # an exception will throw
throw std::invalid_argument("received negative value"); //example #2 of negative throw exception
}
}
// cout << "Interest rate cannot be negative. Enter the amount: ";
mort1.setIntrest(interest);
cout << "Enter the length of the loan in years: "; //establishes term of payments
while (!(cin >> years) || years < 0)
cout << "Remainder of loan period cannot be negative. Enter the amount: ";
mort1.setYears(years);
term = pow((1 + ((interest / 100) / 12)), (12 * years)); //simple interest calculation with power calc to establish whole number translation
while (choice != 3) //loop for menu options and clean function exit
{
cout << endl;
cout << "Program to Calculate Mortgage Payments" << endl <<
"1. Monthly Payment" << endl <<
"2. Total Payment" << endl <<
"3. Exit" << endl << endl <<
"Enter an option above: ";
cin >> choice;
if (choice == 1)
cout << "Monthly payment due is " << mort1.getMonthlyDue(term) << "." << endl;
else if (choice == 2)
cout << "Total amount for entire loan payments plus interest is $" << mort1.getTotalDue(term) << "." << endl <<
"Total Interest Paid for this loan amount $" << mort1.getTotalInt(term) << "." << endl;
}
return 0;
}
Your problem is that when you do
mort1.setLoan(loan);
loan will always be 0 unless cin >> loan; throws an std::sting. When you use
{
std::string loan;
try
{
cin >> loan;
}
catch (string loan) //Exception for comma in 'loan' input by user
{
if (loan.find_first_not_of("0123456789.") != std::string::npos) // npos invalid pseudo-index
{
std::cerr << "bad input, must use whole numbers only\n" << endl;
return 1;
}
std::istringstream ins(loan); // Converts the string into a number without punctuation
ins >> loan;
}
}
You have your conversion code from a string into the double1 in the catch statement. You will only ever enter that statement if cin >> loan; throws a std::string which I do not believe will ever happen. Since you never actually update the value of loan in main it stays at the 0 you initialized it with.
You should only be doing error handling in the catch block. The code to convert the string to a double should be handled outside the catch block. I think you need to revisit how exceptions work and you should also look into how scopes can hide names from the outer scope.
1 This is also not going to work since you are hiding the double loan from main with the string loan declared inside the sub scope. You need to use different names for the variables in the sub scope.