queue assignmentttt

#include <iostream>
#include <queue>
using namespace std;

int main()
{
queue<char> q;
char a;
cout << "Enter a sentence/phrase: " << endl;
while ( cin.get ( a ) && a != '\n' )
q.push(a);
while ( !q.empty() ) {
cout << q.front();
q.pop();

}
cout<<'\n';

system ("pause");
}



how to fix this one
the output should be

Enter sentence:
program
margorp
Last edited on
I believe queue is FIFO - First In, First Out.

So, if you push the letters, p r o g r a m. Then, when those letters come out of the queue, they're going to be in the same order - p r o g r a m.

Am I wrong?


Try using stack
Last edited on
mpark4656 is correct about queues being FIFO.

Stacks are LIFO - Last In, First Out.

Pushing p r o g r a m should yield m a r g o r p when popping, provided you wait until after the m is pushed. If your program was to pop somewhere in the middle of the pushes, the order might not simply be a reverse of the input.

But if all you are doing is reversing the order of input, why not just iterate through it in reverse?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <string>

void reverse_cout(std::string str) {
	for(std::string::reverse_iterator rit = str.rbegin();
	    rit != str.rend(); ++rit)
	    std::cout << *rit;
}

int main() {
	std::cout << "Enter a sentence/phrase: " << std::endl;
	std::string phrase; std::getline(std::cin, phrase);
	
	reverse_cout(phrase);
	std::cout << std::endl;
	
	return 0;
}

http://ideone.com/BxKD9q

Also it might be worth noting that there is a function in <algorithm> called reverse.
http://www.cplusplus.com/reference/algorithm/reverse/
Topic archived. No new replies allowed.