Printing a list of values using a while loop & sentinel

I have to print values entered in by the user, using a while loop and a sentinel value of -1 to indicate the end of the input. For example, if the inputs are "4 5 -1" then the output should be "INPUTS: 4 5". I'm not sure how to print all of the values out separately like a list.

This is what we were given to start with:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
using namespace std;
int main()
{
   int num, sum;

   cout << "INPUTS = ";
   while ()
   {
   
   }
   

   cout <<endl; return 0;  //DO NOT DELETE
}
Last edited on
you need one decision in the while(decision) to tell program when to stop, so it will be !=-1.

and you can use cin>> to get input from user.

when decision is !=-1, so when user type -1 in any moment, it will jump out while loop and continue the rest.
Ok, so I came up with this but the output is still wrong.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
using namespace std;
int main()
{
   int num, sum;

   cout << "INPUTS = ";             
   while (num != -1 )
   {
    cin >> num;
    cout << num << " ";
   }
   
   cout <<endl; return 0;  //DO NOT DELETE
}


When I input "4 5 -1", the output is "4 5 -1" when it should be "INPUTS = 4 5"
Think about the logic you're implying.

1. While the sentinel hasn't been reached..
2. Get input..
3. Output input...

When the sentinel is reached it will know to stop grabbing input, but it has to grab the sentinel as well in the buffer.. The sentinel doesn't just disappear.

Think about what you could put to prevent outputting the sentinel along with your numbers..

Think about this:
if you don't find the sentinel, then print out stuff. Otherwise don't do anything.

1
2
3
cin >> num;
if(num!=-1)
cout << num << " ";
Thanks a lot for your help a3625799132 & shamieh!

I got it correct.
Also, if I were you would I would set a global constant for sentinel. i.e.

1
2
//Global Variables
const int SENTINEL = -1;
Topic archived. No new replies allowed.