My main program ends abruptly when this function is in it:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
void provideHelpIfNecessary(void)
{
char answer;
cout <<"Do you need help (Y/N)? :";
cin >> answer;
if (isValidResponse(answer) == false) {
cout << "Invalid response! Try again.\n" << endl;
provideHelpIfNecessary();
}
elseif (isValidResponse(answer) == true) {
if (isYesResponse(answer) == true) {
cout << "Enter an infix expression at the prompt.\nThe program will\
tell you its value.\nTo stop the program, just hit 'return' at the prompt.";
}
elsereturn; }
}
and this is the snippet of code in main():
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
int main(void)
//
//
...
//
{
while(true){
provideHelpIfNecessary();
cout << "Expression? ";
string expr; // holds the supposed expression
getline(cin,expr);
if (expr.length() == 0)
break;
//
//
...
//
with provideHelpIfNecessary() in there, the program stops right after outputting "Expression? ", and without it in there, it runs fine.
anyone see something wrong that I should fix?
I'm not allowed to change anything in main(). Pre-written by my professor.
But I tried your suggestion anyways just to check it out, and it seems to brings the program back to the beginning after solving every expression, which is not supposed to happen. It's supposed to go only as far back up as "Expression? "
The closest simple alternative to the cin >> ws trick is this:
4 5 6 7
cout <<"Do you need help (Y/N)? :";
cin >> answer;
cin.ignore(); // Alternatively, 'cin.ignore(numeric_limits<streamsize>::max(), '\n');'
// if you can #include <limits>
but that doesn't fix the other problem (which I'm not sure I understand correctly).
Right, that does fix the exiting problem, but not the other.
So the first that should run is provideHelpIfNecessary(). And then the program should output "Expression? " , followed by the user inputting an expression and seeing the result. The program should automatically loop back to outputting "Expression? ", accepting an input, and outputting the result. This is how it should be. But with cin.ignore(), it loops all the back to the beginning of main(). That is the problem.
void provideHelpIfNecessary(void)
{
staticbool isFirstRun = true;
if (isFirstRun)
{
isFirstRun = false;
char answer;
do
{
cout <<"Do you need help (Y/N)? :";
cin >> answer;
cin.ignore();
if (isValidResponse(answer) == false) {
cout << "Invalid response! Try again.\n" << endl;
}
} while (!isValidResponse(answer));
if (isYesResponse(answer) == true) {
cout << "Enter an infix expression at the prompt.\nThe program will\
tell you its value.\nTo stop the program, just hit 'return' at the prompt.";
}
}
}