A minor issue with the Queue code

There is a minor issue with my Queue code below and I would appreciate anyone who can point out where I possibly did wrong. The code is supposed to read integers into a queue, and when one types 'n' instead it pulls the next integer waiting in line from the queue, and when one types 'o' instead it pulls all the integers left in the queue. I have the first two functions work just fine, and yet when I type 'o' for the first time it just won't pull all the integers until I type 'o' again...if you test it out, you would notice how weird it is.

My question is: what the heck is wrong with this code? >_<
Thanks!

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
#include <iostream>
#include <string>
#include <queue>

using namespace std;

bool get_int(istream& in, int& input){
	
	if (in >> input)
		return true;
	in.clear();
	return false;
}

bool should_get_next(istream& in){
	char ch;
	if (in>>ch && ch == 'n')
		return true;
	in.clear();
	return false;
}

bool output(istream& in){
	char ch;
	if (in>>ch && ch == 'o')
		return true;
	in.clear();
	return false;
}

int main(){
	queue<int> q;
	cout<<"Please enter numbers to queue up or 'n' for next item or 'o' to get all the rest elements in queue."<<endl;

	while(true){
		int input_int;
		if(get_int(cin, input_int)){
			q.push(input_int);
			cout<<"Pushed "<<input_int<<" to the queue, current length is: "<<q.size()<<endl;
		}
		else if(!q.empty() && should_get_next(cin)){
			int next = q.front();
			q.pop();
			cout<<"The next item on the queue was: " <<next<<endl;
		}
		else if(!q.empty() && output(cin)){
			while(true){
				int e = q.front();
				q.pop();
				cout<<"The queue have "<<e <<" left."<<endl;
				if (q.empty()) break;
			}
		}
		else break;
	}
	
	return 0;
}
Last edited on
when you press o your get_int function executes. The input fails, and the program moves to the should_get_next function call the o is removed from the input stream and shoud_get_next retruns false. Then your output function executes the o was already removed from the input stream in your should_get_next function so the program waits for you to enter another character.

maybe this will work
1
2
3
4
5
6
7
8
9
10
11
12
bool should_get_next(istream& in){
	char ch;
	ch = cin.peek();
	if (ch == 'n')
	{
		in >> ch;
		return true;
	}
	
		in.clear();
	return false;
}
Last edited on
It does work now! Marvelous! Thanks so much! :) Do you mind also explaining what istream::peek() does here? I searched it online and it says peek() returns the next istream value without extracting it, but how does that help with this problem?
Last edited on
Topic archived. No new replies allowed.