1+ #include < iostream>
2+ #include < string>
3+ #include < limits>
4+ #include < stdexcept>
5+
6+ #include " CurrencyConverter.h"
7+
8+ double getValidAmount () {
9+ double amount;
10+ while (true ) {
11+ std::cout << " Enter amount to convert: " ;
12+ if (std::cin >> amount) {
13+ if (amount > 0 ) {
14+ return amount;
15+ } else {
16+ std::cout << " Please enter a positive amount." << std::endl;
17+ }
18+ } else {
19+ // This handles non-numeric input
20+ std::cout << " Invalid input. Please enter a number." << std::endl;
21+ std::cin.clear (); // Clear the error flag
22+ // Discard the invalid input from the buffer
23+ std::cin.ignore (std::numeric_limits<std::streamsize>::max (), ' \n ' );
24+ }
25+ }
26+ }
27+
28+ // Helper function to get a valid currency code from the user
29+ std::string getValidCurrency (const std::string& prompt, CurrencyConverter& converter) {
30+ std::string code;
31+ while (true ) {
32+ std::cout << prompt;
33+ std::cin >> code;
34+
35+ // Convert input to uppercase to be safe
36+ for (auto &c : code) c = toupper (c);
37+
38+ if (converter.isCurrencySupported (code)) {
39+ return code; // Valid currency
40+ } else {
41+ std::cout << " Invalid or unsupported currency code. Please try again." << std::endl;
42+ converter.printAvailableCurrencies ();
43+ }
44+ }
45+ }
46+
47+
48+ int main () {
49+ // 1. Create an instance of our converter.
50+ // This calls the constructor and loads the rates.
51+ CurrencyConverter converter;
52+
53+ std::cout << " Welcome to the C++ Currency Converter!" << std::endl;
54+
55+ // 2. Main application loop
56+ while (true ) {
57+ std::cout << " \n ------------------------------------" << std::endl;
58+ converter.printAvailableCurrencies ();
59+
60+ // 3. Get all user inputs
61+ std::string from = getValidCurrency (" Convert FROM (e.g., USD): " , converter);
62+ std::string to = getValidCurrency (" Convert TO (e.g., EUR): " , converter);
63+ double amount = getValidAmount ();
64+
65+ // 4. Perform conversion and handle errors
66+ try {
67+ double result = converter.convert (amount, from, to);
68+
69+ // Print the result
70+ std::cout << " \n --- Result ---" << std::endl;
71+ std::cout << amount << " " << from << " = " << result << " " << to << std::endl;
72+
73+ } catch (const std::exception& e) {
74+ // This will catch errors we threw in our .convert() function
75+ std::cout << e.what () << std::endl;
76+ }
77+
78+ // 5. Ask to go again
79+ std::cout << " \n Do you want to perform another conversion? (y/n): " ;
80+ char choice;
81+ std::cin >> choice;
82+ if (choice != ' y' && choice != ' Y' ) {
83+ break ; // Exit the while loop
84+ }
85+ }
86+
87+ std::cout << " Thank you for using the converter. Goodbye!" << std::endl;
88+ return 0 ;
89+ }
0 commit comments