I have 2 functions inputCheck and getInputs. When I call inputCheck function inside the getInputs function it returns false or true depending on inputs. But when it returns false, getInputs function doesn’t stop and keeps giving outputs. In the main function, I call getInputs twice if this is related somehow.
bool inputCheck(int value, string type) {
if (value < 0) {
cout << "Number of " << type << "cannot be smaller than 0.";
return false;
}
return true;
}
bool getInputs(string usage, int& minutes, int& sms, int& internet, int& add_minutes, int& add_sms, int& add_internet) {
cout << "Please enter how many minutes you used this month " << usage << ": ";
cin >> minutes;
inputCheck(minutes, "minutes ");
cout << "Please enter how many SMSs you sent this month " << usage << ": ";
cin >> sms;
inputCheck(sms, "SMSs ");
cout << "Please enter how many MBs you used this month " << usage << ": ";
cin >> internet;
inputCheck(internet, "MBs ");
cout << "Please specify how many additional packages you bought for calls, SMS and internet in this order: ";
cin >> add_minutes;
inputCheck(add_minutes, "additional minutes packages ");
cin >> add_sms;
inputCheck(add_sms, "additional sms packages ");
cin >> add_internet;
inputCheck(add_internet, "additional internet packages ");
return true;
}
I tried using "if" for inputCheck but it didn’t work out. I need any suggestions to fix it, thanks.
>Solution :
Why would the getInputs function stop? You haven’t written any code to make it stop. A return in one function only stops that function, it doesn’t stop any other function.
What I think you are trying to write is this
bool getInputs(string usage, int& minutes, int& sms, int& internet, int& add_minutes, int& add_sms, int& add_internet) {
cout << "Please enter how many minutes you used this month " << usage << ": ";
cin >> minutes;
if (!inputCheck(minutes, "minutes "))
return false;
cout << "Please enter how many SMSs you sent this month " << usage << ": ";
cin >> sms;
if (!inputCheck(sms, "SMSs "))
return false;
...
return true;
}
This code checks the return value of inputCheck
if (!inputCheck(sms, "SMSs "))
and if it is false then it stops the getInputs function.
return false;