Your code will fail if there are more than 1000 numbers in the input. You don't need to read all input and then generate output. You can read a number, print a number, and repeat until you read 42.
I assume that you are testing your code from a console screen. For the input:
1
2
42
Your code will output:
12
Your code should output:
1
2
This will be more obvious if you redirect stdin and stdout to files. A quick google search will help you with that.