I have been asking in previous questions about how to get multiple string inputs to control the flow of the program, using if else statements. and everything worked out fine.
the code for the YES and NO is fantastic and i’m very happy, except I built a test rig in the form of a function that is called again and again if the user doesn’t type exit.
The reason i did this was so i could just try all different combinations of words to see how durable the std::string is, whats the limits and such. the only issue is that after the code loops once (it goes back to main and into the function YESNO again) then the input goes the yes or no part as its meant to but instead of looping for a second or third time the program closes.
heres the code:
#include <iostream>
#include <algorithm>
#include <cctype>
#include <string>
//the above headers are for the control flow code (transforms i think)
using namespace std;
int YESNO (int var);
int main()
{
int loop=0;
if (loop == 0)
{
YESNO(0);
loop=YESNO(0);
}
else
{
cout << "\n " << endl;
}
return 0;
}
int YESNO (int var)
{
cout << "This is a simple yes or no program control flow test" << endl;
cout << "Please enter yes or no in different ways to test the code, many thanks!!!" << endl;
cout << "\nYES or NO or exit?" << endl;
string input ="";
cin >> input;
//all good, the above i know how todo
transform (input.begin(), input.end(), input.begin(), tolower);
if ((std::string::npos != input.find( "yes" )) || (std::string::npos != input.find( "y")) )
{
cout << "You entered yes!! " << endl;
}
else if ((std::string::npos != input.find( "no" )) || (std::string::npos != input.find( "n")) )
{
cout << "You entered no!! " << endl;
}
else if (std::string::npos != input.find( "exit" ))
{
var=1;
}
else
{
cout << "ERROR REPEAT..........!!!" << endl;
var=0;
}
return(var);
}
The idea was that once the user types in yes or no then the function automatically repeats so the user (me) can type in yes or no again to see how far we can push std::string, and typing exit will cause the program not to loop as loop will no longer equal 0 and the program will close.
the loop works but the function doesn’t behave correctly, and its goes straight to exist after running cout for the correct response.
There are no looping constructs in your program. Instead, you’re invoking
YESNOtwice via explicit calls.Try any of the following:
or
or
or
Some notes on style:
return(var);, instead justreturn var;yesNooryes_novarortmp, your variables should describe their purpose and/or contentYESNOto take an argument so it somewhat clutters things up