Okay, I'm working through Bjarne Stroustrup's Programming: Principles and Practice using C++ (really enjoying it!) and I've completed the first "Try This" exercise of Chapter 4 (Page 104). The code is as follows:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
|
// Try This - Chapter 4: Page 104
// this programme will convert yen, euros and pounds into dollars
#include <iostream>
using namespace std;
int main()
{
// create conversion constants
const double yen_to_dollar = 0.012044;
const double euro_to_dollar = 1.2932;
const double pound_to_dollar = 1.5548;
cout << "Please enter a value followed by a unit (y, e or p): ";
double value;
char unit;
cin >> value >> unit;
if (unit == 'y')
cout << value << "yen == $" << value*yen_to_dollar << endl;
else
{
if (unit == 'e')
cout << value << "EUR == $" << value*euro_to_dollar << endl;
else
{
if (unit == 'p')
cout << value << "GBP == $" << value*pound_to_dollar << endl;
else
cout << "Sorry, I don't recognise that unit!\n";
}
}
return 0;
}
|
My style is not exactly like that of Bjarne's (I've read half of Accelerated C++ and done a few other web tutorials before) but I have picked up a few things I like and dislike when it comes to readability.
The code compiles without a hitch (on g++ anyway) and seems to run as intended:
Please enter a value followed by a unit (y, e or p): 100p
100GBP == $155.48 |
Please enter a value followed by a unit (y, e or p): 100y
100yen == $1.2044 |
However...
I come across a problem whenever I try to convert from Euros to Dollars:
Please enter a value followed by a unit (y, e or p): 100e
Sorry, I don't recognise that unit! |
but when I space the value and char it works perfectly:
Please enter a value followed by a unit (y, e or p): 100 e
100EUR == $129.32 |
I wanted to know if it had anything to do with the actual mathematical value of "e" but inputs like "100ep" and "100e y" both give the result, "Sorry, I don't recognise that unit!" so that mustn't be the case.
Does anyone have any ideas as to why the lack of a simple "space" can bring this programme to its knees?
P.S.
In case anyone asks, I'm running Ubuntu 10.10 64-bit