1

I am using priority queue from the C++ STL library and I want to keep pushing elements into the queue till the user presses Enter.

I've tried using getchar() to get the input of the elements but it gets saved as a series of 1's in the queue.

priority_queue<int> v1;
priority_queue<int, vector<int>, greater<int> > v2;
cout<<"Enter the elements of the queue. Press enter to stop.\n";
while(a = getchar()!= '\n')
{
    v1.push(a);
    v2.push(a);
}
while(!v1.empty())
{
    cout<<v1.top()<<" ";
    v1.pop();
}

I expected the output to be the min and max heap of the elements entered, but all it gives me is a series of 1's

Nacho Libre
  • 404
  • 5
  • 18

2 Answers2

3
while(a = getchar()!= '\n')

it gives me is a series of 1's

warning with the priority of the operators, you want

while((a = getchar())!= '\n')

currently you do like

while(a = (getchar()!= '\n'))

while the input char is not newline the test is true so a is set to 1


Considering your remark below you want to read lines then stop if that line is empty or just contains the newline or may be also if the line does not contains a literal int, else to extract the int to push it

For instance :

#include <iostream>
#include <queue>
#include <string>
#include <sstream>

using namespace std;

int main()
{
  priority_queue<int> v1;
  priority_queue<int, vector<int>, greater<int> > v2;
  cout<<"Enter the elements of the queue. Press enter to stop.\n";

  int a;
  string s;

  while (getline(cin, s) && (istringstream(s) >> a))
  {
    v1.push(a);
    v2.push(a);
  }
  while(!v1.empty())
  {
    cout<<v1.top()<<" ";
    v1.pop();
  }
  cout << endl;
}

Compilation and execution :

pi@raspberrypi:/tmp $ g++ -pedantic -Wall -Wextra c.cc
pi@raspberrypi:/tmp $ ./a.out
Enter the elements of the queue. Press enter to stop.
12
32

32 12 
pi@raspberrypi:/tmp $ 
bruno
  • 32,150
  • 7
  • 23
  • 37
0

Yes, because a = getchar()!= '\n' is evaluated as a = (getchar() != '\n') gives you a bool value, true in this case, until you press enter.

A.Franzen
  • 715
  • 4
  • 10