Cin object being weird in loops.

'Ello. I've recently decided to pick up programming. The books I bought have been doing me well, however, I have one problem that I don't have answered. I was going to write a program to find the mode of the elements in a vector until one glaring problem I've been having reoccured. Here's my code up to this point:

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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#include <iostream>
#include <vector>
using namespace std;

int get_int();
bool get_confirm();

int main () {
    vector<int> v_userinput;
    int userinput = 0;
    bool get_vector = true;
    cout << "Enter your numbers: " << endl;
    do {
        userinput = get_int();
        v_userinput.push_back(userinput);
        get_vector = get_confirm();
    } while (get_vector);
    return 0;
}

int get_int() {
    int number;
    while (1) {
        number = 0;
        cin >> number; // Problem!!!
        if (cin.good()) {
            return number;
        } else {
            cout << endl << "Invalid input.";
        }
    }
}

bool get_confirm() {
    char yorn = 'Y';
    cout << "Continue? Y or N: ";
    while (1) {
        bool is_yorn = false;
        bool valid_choice = false;
        while (!is_yorn) {
            while (!valid_choice) {
                cin >> yorn; // Problem!!!
                if (cin.good()) {
                    valid_choice = true;
                }
                if (!valid_choice) {
                    cout << "Invalid input." << endl;
                }
            }
            if (yorn != 'Y' && yorn != 'N' && yorn != 'y' && yorn != 'n') {
                is_yorn = false;
                valid_choice = false;
                cout << "Invalid input." << endl;
            }
        }
        if (yorn == 'Y' || yorn == 'y') {
            return true;
        } else {
            return false;
        }
    }
}


The problem is in the get_confirm function, in the loops on lines 41 and 25 . It seems to completely ignore "cin >> number" on any consecutive loops. I have no idea what causes this behavior, so any help explaining as to why it does so would be appreciated, along with any other possible improvements to the existing code.

Edit: Correction, not exactly an infinite loop.
Last edited on
It's not cin that's weird... it's your logic. =)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
bool get_confirm() 
{
	char input ;
	cout << "Continue? Y or N\n" ;
	while ( cin >> input )
	{
		if ( input == 'y' || input == 'Y' )
			return true ;
		if ( input == 'n' || input == 'N' )
			return false ;

		cout << "InvalidInput.\nContinue? Y or N\n" ;
	}
}
Topic archived. No new replies allowed.