Issue with sample code in C++

I'm still new to C++, so I don't know a great deal about the language or it's features. I bought a book called C++ Primer 5th edition released (I believe) in 2013. There is a block of code that it uses as an example that for some reason is not working at all for me. I'm using Microsoft Visual Studios 2013, in case that helps. The code is as follows:

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
using namespace std;

int main()
{
	int sum = 0, value = 0;
	//read until end of file, calculating a running total of values read
	while (cin >> value)
		sum += value;
	cout << "Sum is: " << sum << endl;
	cin.get();
	return 0;
}

This program is 99% identical to what's in the book. the ONLY difference is that I declared the namespace std at the beginning of my program.

According to the book, I should be able to enter a custom amount of integers and the program will store them all, add them together and print out the sum. the book uses the example:

1
2
3
4
If we give this program the input:
  3 4 5 6
then our output will be:
  Sum is: 18 

But this isn't the case. When I run the program, and I enter 3 4 5 6 (with spaces) it simply pulls down to a new line and doesn't progress. I can continue hitting 'Enter' and it continues to go to new lines.

I tried using braces '{}' in various spots for the 'while' loop, but the closest I got was it printing Sum is: 18 after every individual number. i.e.:

1
2
3
4
5
3 4 5 6
Sum is: 3
Sum is: 7
Sum is: 12
Sum is: 18

I have checked, double checked, and triple checked. I'm doing everything the same as in the book, and yes, I attempted removing using namespace std; from the top of the program and declaring every cin and cout etc.
Last edited on
You need to terminate the data entry by either entering EOF (CTRL-D or CTRL-Z) or some other value that will cause the input stream to fail.
Thank you jlb. You are a true gentleman and a scholar
Topic archived. No new replies allowed.