John Davidson

c++ - Recursive function does not return specified value

0 comments
Message:


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.



My Answer:
>> price;__ if (price < 0) {_ cout << "Price cannot be negative. Please enter a valid price: ";__ load_price();__ } else {_ tempGd->setPrice(price);__ }__ return tempGd->getPrice();_}_I am expecting the function to return the price value when the input is valid. However, when I call the function and check the returned value, it is always 0. What could be causing this issue?

Rate this post

3 of 5 based on 4929 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us