Incorrect Output

Hello,

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?

Here's my program:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <iostream>
#include <string>
#include <cstdlib>

using namespace std;

string hit_or_stand()
{
    string response;

    cout << "Hit (h) or Stand (s)? ";

    while (cin >> response)
    {
        if (response == "h")
            return "h";
        else if (response == "s")
            return "s";
        else
        {
        cin.clear();
        cin.ignore();
        }

        cout << "Hit (h) or Stand (s)? ";
    }
}

int main()
{
    if (hit_or_stand() == "h")
        cout << "hit";
    else if (hit_or_stand() == "s")
        cout << "stand";

    return 0;
}



Here's a screenshot of the output:
http://i1130.photobucket.com/albums/m521/silver1x/program.png
@silver1x

Try it this way.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
// Hit or Stand.cpp : Defines the entry point for the console application.
//

#include <iostream>
#include <string>
#include <cstdlib>

using namespace std;

string hit_or_stand()
{
    string response;

    cout << "Hit (h) or Stand (s)? ";

    while (cin >> response)
    {
        if (response == "h")
            return "h";
        else if (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";
    else if (option == "s")
        cout << "stand";

	cout << "\n\n";  // just adding a couple newlines.

    return 0;
}
Hey thanks whitenite1!

It works well now, but could you explain why the code I have did not work? Anyways, I appreciate it.
@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.
Topic archived. No new replies allowed.