0

I am trying to debug a recursive function used to validate user input and return a value when the input is OK. The function looks like this:

double load_price()
{
    double price;

    Goods * tempGd = new Goods();

    cin >> price;

    while (!cin)
    {
        cin.clear();
#undef max
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
        cout << endl;
        cout << "You didn't enter a number. Do so, please: ";
        cin >> price;
    } // endwhile
    if (!tempGd->set_price(price))
    {
        cout << endl;
        cout << "The price " << red << "must not" << white << " be negative." << endl;
        cout << "Please, insert a new price: ";
        load_price();
    }
    else
    {
        delete tempGd;
        return price;
    }
}

The method set_price() of Goods class looks as follows

bool Goods::set_price(double price)
{
    if (price> 0)
    {
        priceSingle_ = price;
        priceTotal_ = price* amount_;
        return true;
    }
    return false;
}

I tried drawing the problem on a paper but all my diagrams seem to look the way my function already looks like. I think there are some problems with returns, but I do not know where.

Help would be greatly appreciated.

Andrew
  • 73
  • 1
  • 7

2 Answers2

5

You're not using the return value of the recursive call. You need to do:

return load_price();
Barmar
  • 741,623
  • 53
  • 500
  • 612
1

Who talked you into using recursion for that problem?

#undef max
double load_price()
{
   for(;;) {
      double price;
      cin >> price;
      if (!cin)
      {
         cin.clear();
         std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
         cout << endl;
         cout << "You didn't enter a number. Do so, please: ";
         continue;
      }
      if (!Goods().set_price(price))
      {
         cout << endl;
         cout << "The price " << red << "must not" << white << " be negative." << endl;
         cout << "Please, insert a new price: ";
         continue;
      }
      return price;
   }
}
Hans Klünder
  • 2,176
  • 12
  • 8
  • Thank you for the iterative solution. To be honest I was trying to find one but could not wrap my head around it. I will use yours, if you don't mind. I do not really like recursion, just could not figure the iterative solution out. – Andrew Dec 29 '14 at 15:50
  • Of course, feel free to use it. I won't post anything here if I don't want people to use it. – Hans Klünder Dec 29 '14 at 15:52
  • Thank you once again, Hans. I altered my other 2 recursive methods using your template, methods I used to check for inserted ID and amount of Goods. – Andrew Dec 29 '14 at 16:04