This exhibits multiple varieties of undefined behavior. This should be handled with ::std::vector
and ::std::string
. You should largely never be using new
directly in any code you write.
First, you allocate an int
but never initialize it. Then you test it to see if it's value is '\n'
(which happens to be 10), but accessing the integer before it's initialized is undefined behavior.
Next, you read in an integer, and then increment i to 1, then access b[i]
, which is again undefined behavior because you're reading memory that you've never allocated. You allocated space for one int
, and you're trying to access a second.
The fact your are confused about why this code doesn't work tells me that you have some really significant misunderstandings about a number of different things.
For example, even without the undefined behavior problems I just mentioned, your loop test would never test the most recently read value, it always tests a value that you haven't yet read.
And also, if you enter a blank line, the read won't even return. That's whitespace, and whitespace is simply skipped over by the iostream library when you ask for an int
. Even if you were checking the most recently read value in your while loop, you would have to enter 10
to get your program to stop, not a blank line.
My suggestion would be to find a TA to help you. The number of misunderstandings and mistakes in this simple snippet of code is too hard to unwind in a StackOverflow question without simply telling you what the answer is. And this looks a lot like homework. I'm not going to tell you what the answer is.