Whats wrong with my code?

Hey, first off, this is my first time here, hopefully I will be able to give back to the community as my knowledge and programming skills are increased.

I started out in VB6 (stop laughing!) in my high school, and was gunna take AP Java, but it was canceled for the year when only 11 people signed up. Anyway, since then I have been (trying) to teach myself c++, and have just started getting a little more serious about it.

Anyway, I was wondering if someone could tell me what is wrong with this code:

After 9 you might stop typing stuff, but it is still waiting for user input.
Your while loop gets user input, runs it and waits for user input again, goes again and waits again. Just because you stop typing in does not mean it stops waiting for user input. In keeps waiting and waiting until it gets input or you forcefully stop the program.

By default, operator>> treats a space and a newline the same. So when you hit enter sending your input to the function, it is adding a newline to the stream. That has basically the same effect as if you had put a space in the stream. That is why the loop isn't broken when the user hits enter.

If you want to get only the values input before the user hits enter, you would want to use getline to read the line into a string, then put that into a stringstream and replace cin in your current code with the stringstream variable. That is probably a bit complicated at the moment for you, so I'd suggest using the -1 idea.

You could also have the user type in a letter, which will make the input fail and break the loop. That will work well for your simple program, but the problem is that if you want to use cin again later in the program, you have to remember to clear the fail state and ignore the bad character(s).

BTW, Enahs' example code has a minor problem if you try to use it with -1. It fails to check th einput before adding it to the sum, so if the user enters the sentinel (-1 in this case), that value will be added to the sum when it isn't meant to be. It only doesn't matter if the sentinel is 0 because it won't change the sum any.

Wouldnt it fail at the end of the file? It ends (and gives me the sum) when I press ctrl +z (the manual way to tell it end of file) But it seems as though that event isnt triggering.

There is a bug in MS Windows that prevents detection of the end-of-file character correctly. Try pressing Ctrl+Z and then ENTER. That's usually what I have to do. Here's a link to Bjarne Stroustrup's example for working around this bug: