Codecademy / learn-cpp

Codecademy | Learn C++
https://www.codecademy.com/learn/learn-c-plus-plus
715 stars 334 forks source link

C++ for programmers - Piggy Bank issue #91

Open Armocalypsis opened 2 months ago

Armocalypsis commented 2 months ago

Hi all!

I wrote some additional code as part of the Piggy Bank exercise to retake input values if they are not valid (i.e. while std::cin has an error flag, retake value), and it throws me an infinite loop when I click save. I was wondering if this is an error on my part, or that this is an error of whatever tests are run to check for errors. If it is the latter, I think this should be accounted for in whatever tests this exercise runs, as error checking is not impossible to implement at this skill level even if it is not part of the exercise steps.


#include <iostream>

/*
pesos to USD = 0.05
reais to USD = 0.18
soles to USD = 0.27
*/

double pesos, reais, soles;
double dollars;
double take_input(void) {
  double currency;
  std::cin >> currency;
  /* the below should be a while loop, but this only works if I check for correct input a limited number of times */
  if (std::cin.fail()) {
    std::cin.clear();
    std::cin.ignore();
    std::cin >> currency;
  }
  return currency;
}

int main() {
  std::cout << "Enter number of Colmbian Pesos:";
  pesos = take_input();
  std::cout << "Enter number of Brzilian Reais:";
  reais = take_input();
  std::cout << "Enter number of Peruvian Soles:";
  soles = take_input();
  std::cout << "Pesos: " << pesos << ", Reais: " << reais << ", Soles: " << soles << "." << std::endl;
  dollars = (0.05 * pesos) + (0.17 * reais) + (0.27 * soles);
  std::cout << "US Dollars = $" << dollars << std::endl;
}