super simple currency converter switch acting oddly? - c++

This was an exercise from Principles and Practice Using C++ to make a basic currency converter using if checks then to remake it with switches. Everything runs pretty good except or my middle switch. It doesn't seem to work like the rest of the program. Every other one is fine with me entering in data like 111y, 111p but when working with euros it NEEDS a whitespace or else it will go to the default switch. I did a break point and currency is not being set to e or E and it's only with the euros!
I hope it isn't anything too silly, but it's got me confused Bjarne doesn't explain this one :P I don't have #include iostream in the code because it's all handled with *std_lib_facilities* Just wanted to say that before someone points it out XD
#include "std_lib_facilities.h"
using namespace std;
int main()
{
double dollar = 0;
char currency = ' ';
const double yen = 0.010;
const double euro = 1.31;
const double pound = 0.65;
double sum = 0;
cout << "Please enter amount and Y for yen or E for Euro or P for pound.\n";
cin >> dollar >> currency;
switch(currency)
{
case 'Y': case'y':
{
sum = dollar * yen;
cout << dollar << " is equal to " << sum << " yen.\n";
break;
}
case 'E': case'e':
{
sum = dollar * euro;
cout << dollar << " is equal to " << sum << " euro.\n";
break;
}
case 'P': case'p':
{
sum = dollar * yen;
cout << dollar << " is equal to " << sum << " pound.\n";
break;
}
default:
cout << "Wrong values...\n";
break;
}
keep_window_open();
return 0;
}

Since dollar is a double, the E or e gets interpreted as part of the exponent of the number (as in 2e-2) when you extract it. Since there are no digits after it, the extraction does not complete and cin goes into the fail state. The read of currency is then skipped, never changing it from the initial value of ' '. When you enter a space, the extraction of dollar ends at the space and currency is read as expected.
To fix it, you could try several things. You could require a space between the amount and the currency indicator. You could read it in as a string and attempt to parse it yourself. You could pick a different symbol for euros.
In any case, you should check the state of the cin after you're done reading from it.

Related

Char to static_cast<int> works but char[7] to static_cast doesn't

I am working on a project for class that wants me to convert a string of letters to numbers, I did not use switch statements because that would be dumb and too long, so I made the following program. However, the problem with it is that I can only do one letter at a time due to it being a char and the static_cast<int>(phrase) will not work if I try to do this: char phrase[7]; it will give me 3 errors (I cant remember what they are at this moment, I will edit later today to include errors). I can't use certain code as well, like stoi and atoi as we have not gone over them in my textbook yet. So if you can give multiple different takes on this problem it would be greatly appreciated! Thank you! Also, if you can make sure the code would works with my program that would be even better! I left the char phrase[7] in the code so if you want to copy and paste to see the errors you can! The assignment is to have the user enter as many letters as they want and return it to them as 123-1234 as the program will only take the first 7 letters (if you can also figure out how to break up the word to allow the dash (-) to be in between that would be cool too.)
Edit:
To make telephone numbers easier to remember, some companies use letters to show their telephone number. For example, using letters, the telephone number 438-5626 can be shown as GET LOAN. In some cases, to make a telephone number meaningful, companies might use more than seven letters. For example, 225-5466 can be displayed as CALL HOME, which uses eight letters. Write a program that prompts the user to enter a telephone number expressed in letters and outputs the corresponding telephone number in digits. If the user enters more than seven letters, then process only the first seven letters. Also output the – (hyphen) after the third digit. Allow the user to use both upper case and lowercase letters as well as spaces between words. The special characters – (hyphen) represents the number 1 and the _ (underscore) represents the number zero. Moreover, your program should process as many telephone numbers as the user wants.
ERRORS:
invalid type conversion
argument of type "char *" is incompatible with parameter of type "int"
expression must be a modifiable Ivalue
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
int main()
{
char phrase[7];
char letter;
int digit;
int num = 0;
cout << "Enter Y/y to convert a telephone number from letters to digits"
<< endl;
cout << "Enter any other key to terminate the program." << endl;
cin >> letter;
while (letter == 'Y' || letter == 'y')
{
cout << "Enter a telephone number using 7 or more letters" << endl;
cout << "for Prefix and number, only the first 7 letters are used." << endl;
cout << "and dashes '-' are ZEROES, underscores '_' are ONES" << endl;
cout << "ALL OTHER SYMBOLS ARE ignored." << endl;
cout << "-->: ";
cin >> phrase;
cout << endl;
phrase = toupper(phrase);
num = static_cast<int>(phrase) - static_cast<int>('A');
if (0 <= num && num < 26)
{
digit = (num / 3) + 2;
if (((num / 3 == 6) || (num / 3 == 7)) && (num % 3 == 0))
digit = digit - 1;
if (digit > 9)
digit = 9;
cout << "The corresponding telephone number is: " << digit << endl;
cout << "To process another telephone number, enter Y/y" << endl;
cout << "Enter any other key to terminate the program." << endl;
cin >> letter;
}
else
cout << "Invalid input." << endl;
}
return 0;
}

One 'case' not working in a simple 'switch' statement

I'm doing some basic stuff from the book "Principles and Practices C++" and I can't work out why the following code doesn't work for the 'euro' output.
If I enter 50e, for example, it gives me the default case and says "Sorry, I don't recognise ' ' as a currency." However, if I type 50 e with a space, it works. None of the other cases require a space.
I can't work out the issue. I know it's basic, but I'm still learning.
Here's the code:
int main()
{
const double yen_to_dollar = 0.0094;
const double euro_to_dollar = 1.24;
const double pound_to_dollar = 1.40;
double amount = 0.0;
char currency = 0;
cout<<"Please enter how much money you have followed by 'e' 'y' or 'p' (for euro, yen or pounds):\n";
cin>>amount>>currency;
switch (currency){
case 'y':
cout << amount << " Yen == " << yen_to_dollar*amount << " Dollars\n";
break;
case 'p':
cout << amount << " Pounds == " << pound_to_dollar*amount << "
Dollars\n";
break;
case 'e':
cout << amount << " Euros == " << euro_to_dollar*amount <<" Dollars\n";
break;
default:
cout << "Sorry, I don't recognise '" << currency << "' as a currency.\n";
}
return 0;
}
To avoid that e.g. 50e is parsed as a floating point number you can read in the line as a string using getline, and find the letter position. Then parse the numerical part (before the letter position) using e.g. std::stod.
For the idea of using an UTF-8 console i/o library (the only reasonable one that comes to mind is my own stdlib) and actual “€” and “¥”, be aware that these characters are represented with more than one char value as UTF-8 (a bit incompatible with direct use of switch, though you could map them to numerical currency id's), and that they can be difficult to type.
That is, UTF-8 console i/o has its own problems for this particular case.

2 identical codes, get error at one

I added comments to the code, do I have a compiler issues? I can't figure it out, I tried looking on google and the book but I cant figure out why the first half of code only accepts the input with space between the number and unit and second code accepts the number and unit together.
I'm using code blocks. So far I tried closing it and opening it again.
int main(){
constexpr double dollar_to_euro = 0.91;
constexpr double dollar_to_yen = 117.07;
constexpr double dollar_to_pounds = 0.70;
double sum = 1;
char curr = '\0'; // tried replacing '\0' with '0' and ' '
cout << "Please enter sum, followed by currency for conversion.\n"
<< "U for dollar, E for euro, Y for yen and P for pounds.\n";
cin >> sum >> curr; // This is my issue, it does not want to accept "sumcurr" together, it only accepts it if theres space in between
// yet on the second code for inches or centimeters it does accept them being together. Look down.
// For example entering "5 E" works, yet "5E" does not work.
if(curr=='E')
cout << "The amount " << sum << " euro is " << sum/dollar_to_euro << " dollars\n";
else
cout << "GOD DAMMIT !!!!\n";
constexpr double cm_per_inch = 2.54;
double len = 1;
char unit = '\0';
cout << "Please enter length followed by unit.\n";
cin >> len >> unit; // Over here it works, this is an example from a book. Entering "5i" works.
if(unit=='i')
cout << len << " in == " << cm_per_inch*len << "cm.\n";
else
cout << "Wrong input !\n";
}
The problem here is that E/e is valid in a floating point number but 5E/5e is not a valid floating point number as you need a value after the E/e. So when you enter 5e the input for sum fails because of the invalid syntax where 5e0 would work. If you use anything other than E/e then it will work like your second example.
For more information on the format of floating point numbers see: Cppreference floating point literal

How to assign an enum value to a double variable defined by the user ?? C++

Hello i am a student so i wanted to say sorry in case my writing is tiring, feel free to correct me .
i am having the following problem i am trying to assign an enum int value to another double variable to make one multiplication.
so the variable costOfRoom should take the value D or T or S which belong to an enum. (D=200 ,T=150,S=110)
this must be done by the user .
But cant find any way , i tried to make the second variable a string type but its not working again. it will just take the chars normally as a string would do :(
Also tried cin >> type_Ofroom costofroom ;
but i think that this is used in Java??
Searched the forum also haven't any similar answer :(
The program runs fine it doesn't have any compiling errors :)
Thanks for your time
/* build a software system which will allow a hotel receptionist,
to enter in bookings for guests who come to the desk.
The system should display the room options as:
Room Price Code
---------------------------------------------------------------
Deluxe Room £200 D
Twin Room £150 T
Single £110 S
The receptionist should be prompted to enter in the room type and the number of
nights a guest wishes to stay for and then calculate the amount
they need to pay.
*/
// solution
#include <iostream>
using namespace std;
int main() {
// decleration of variables
double number_OfDays = 0, Totalcost = 0, costofroom = 0;
enum type_Ofroom { D = 200, T = 150, S = 150 };
cout << "enter the type of the room " << endl << endl;
//input of room type
cin >> costofroom; // **here is the problem** i am trying to give the
// values of the enum varaiable
// it should have D or T or S but i cant make it
cout << "enter the number of the days " << endl << endl;
//input of days
cin >> number_OfDays;
// calculation
Totalcost = costofroom * number_OfDays;
// result
cout << "the costumer has to pay " << Totalcost << " pounds" << endl << endl;
return 0;
}
You can read into a double, and then check against your enum values:
//input of room type
while (1)
{
cin >> costofroom;
if (costofroom == 0.0)
costofroom = D;
else if (costofroom == 1.0)
costofroom = T;
else if (costofroom == 2.0)
costofroom = S;
else
{
cout << "You didn't enter a valid option" << endl;
continue;
}
break;
}
However, it would be better to read into an int, and then set your double afterward.
double costofroom;
int option;
...
//input of room type
while (1)
{
cin >> option;
if (option == 0)
costofroom = D;
else if (option == 1)
costofroom = T;
else if (option == 2)
costofroom = S;
else
{
cout << "You didn't enter a valid option" << endl;
continue;
}
break;
}
The user can only input characters. cin will convert groupings of numbers to an int (e.g. 123) or or double (e.g. 123.5). It will also handle non-numeric groupings to std::strings (e.g. hello) or individual characters (e.g. c).
Once you have the user's input, you can convert them to your enum. You can use if statements, case statements or some type of table look up to do this.

C Plus Plus not calculating correctly

I made a program that calculates the area of a circle. You have the option to enter a diameter or a radius. After you select one of them, you enter the value. Then it tells you what you entered and gives you the answer. But the answer isn't correct. For example, I enter 'r' then type '3' it gives me:
This is a calculator that calculates the area of a circle.
To get started, type 'd' (no quotes or caps) to enter a diamater.
Type 'r' (no quotes or caps) to enter a radius.
r
You chose radius, now please enter a number.
3
3 * 2 * 3.14 = 40828.1
It doesn't look right, as you can see. Perhaps C++'s Pi variable is outdated?
#include <iostream>
#include <math.h> // Importing math.h so I can use the M_PI variable.
using namespace std;
int main() {
char choice;
float result = 0.0; // Set to zero to init and stop the IDE from complaining.
float number = 0.0;
cout << "This is a calculator that calculates the area of a circle." << endl;
cout << "To get started, type 'd' (no quotes or caps) to enter a diamater." << endl;
cout << "Type 'r' (no quotes or caps) to enter a radius." << endl;
cin >> choice;
choice = tolower(choice); // Making it lower case so it's easier for compiler to recoginize.
switch (choice) {
case 'r':
cout << "You chose radius, now please enter a number." << endl;
cin >> number;
result = choice*choice*M_PI;
break;
case 'd':
cout << "You chose radius, now please enter a number." << endl;
cin >> number;
result = choice*M_PI;
break;
default:
cout << "You entered an invalid character. Please only enter 'r' or 'd' (no quotes or caps)" << endl;
break;
}
if (choice == 'r')
{
cout << number << " * 2 * 3.14 = " << result << endl;
}
else if (choice == 'd') {
cout << number << " * 3.14 = " << result << endl;
}
else {
cout << "Nothing here cause you didn't do simple stuff correctly..." << endl;
}
return 0;
}
Since you are new couple things you need to remember:
switch case and if/else statement are pretty similar, therefore you don't need to use them both at the same time on same task.
When the program runs the user inputs a value either r or d , that value get passed to the choice variable. The switch case compares its own cases to the choice value and if both value are equal, it will run that case code block and if they are not it will run the default code.
Now inside the case, you are asking for the radius, once you get the radius,
result = number * number * M_PI;
OR
result = pow(number,2.0) * M_PI;
And also there is a big difference between cout<<"2*3"; and cout<<2*3;
The first example will display 2*3 into your screen.
The second example will display the result of 2*3 into the screen
6, the reason you it calculates because there is not quotation mark around it
Hope that helps...
Shoulr calculation of result use choise???
Looks like you have a typo. Replace choise woth number in the
result = choice*choice*M_PI;
And in the
result = choice*M_PI;
Using choise in calculation actually uses its ASCII code. This explains the big values that you get in the result.
result = choice*choice*M_PI;
this should be
result = number * number * M_PI;
also you are printing
* 2 * 3.14 =
should be
^ 2 * 3.14 =