simple problem with list

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
#include <iostream>
#include <list>
using namespace std;

int main()
{
	list<int> lst;

	int val;
	while(cin >> val)
	{
	    while(val % 2 != 0)
	    {
	        cout << val << " is not even number \nTry again...\n";
            cin >> val;
	    }
    lst.push_back(val);
	}

    cout << "\nList values : \n";
	list<int>::iterator p = lst.begin();
	while(p != lst.end())
	{
        cout << *p << " ";
		p++;
	}
	return 0;
}

This program accepts only even numbers.
It is work well with me but when do I print values to the screen from 1 to 9 then I get out from program by pressing any button is not digital, the program prints the number zero at the end of the list, although that I did not print this value

Can someone tell me what is the wrong?
Last edited on
Add lst.pop_back(); after your while loop. I believe what's happening is that you're adding in the "garbage" in the buffer. The pop_back will remove the last item inserted (the garbage).

Another alternative is to use something besides a (cin >> val) condition.
I added it after
1
2
3
4
5
6
7
8
9
10
while(cin >> val)
	{
	    while(checkingValue(val))
	    {
	        cout << val << " is not even number \nTry again...\n";
            cin >> val;
	    }
    lst.push_back(val);
	}
	lst.pop_back();


But now appears new problem when I add 1 then 2, it didn't print 2 on the screen
Last edited on
I just ran your original program and I don't notice this zero you're talking about. Here is my output:
2
4
6
8
^Z

List values :
2 4 6 8
Sigh...

This is because . represents 0.0. This is the int 0. 0 is even (according to your while statement) so it get's added to your list. You display numbers 2 4 6 8 0 because all of those numbers are in your list.

Why are you entering a period anyways?
I don't know why ^_^

thank u so much
Topic archived. No new replies allowed.