I have a function that's asks the user to "hit or stand" by entering "h" or "s" and any incorrect input will ask the question again. Then in my main function, it outputs whether the user chose to hit or stand. When I run my program everything runs correctly, but the only problem is when I type in "s" to stand, the program outputs the question again, then I will have to type in "s' again for it to output "stand." Does anyone know why this is the case?
// Hit or Stand.cpp : Defines the entry point for the console application.
//
#include <iostream>
#include <string>
#include <cstdlib>
usingnamespace std;
string hit_or_stand()
{
string response;
cout << "Hit (h) or Stand (s)? ";
while (cin >> response)
{
if (response == "h")
return"h";
elseif (response == "s")
return"s";
else
{
cin.clear();
cin.ignore();
}
cout << "Hit (h) or Stand (s)? ";
}
}
int main()
{
string option; // added a new string variable
option = hit_or_stand(); // get 's' or 'h' from routine
if ( option == "h") // checks what 'option' is equal to
cout << "hit";
elseif (option == "s")
cout << "stand";
cout << "\n\n"; // just adding a couple newlines.
return 0;
}
@silver1x
After calling a function, control is sent back to the next line immediately following the calling line. I am surprised that it doesn't just print 'hit'. Maybe because it's still in the 'if' function. And mostly, I think, because 'response' is a variable only known to the function hit_or_stand.