C++ Primer 5th Edition code (1.4.4)

Hi, I'm a complete noob to programming. I'm working my way through C++ Primer, 5th edition*. I have understood the examples so far, as well as worked through their exercises, but this one from 1.4.4 (Flow of Control - The "If" Statement) has me stumped:

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 "stdafx.h"
#include <iostream>
int main()
{
	// currVal is the number we're counting; we'll read new values into val
	int currVal = 0, val = 0;
	// read first number and ensure that we have data to process
	if (std::cin >> currVal) 
	{
		int cnt = 1;  // store the count for the current value we're processing
		while (std::cin >> val) 
		{ // read the remaining numbers
			if (val == currVal)  // if the values are the same
				++cnt;  // add 1 to cnt
			else 
			{ // otherwise, print the count for the previous value
				std::cout << currVal << " occurs "
					<< cnt << " times" << std::endl;
				currVal = val;  // remember the new value
				cnt = 1;  // reset the counter
			}
		}  // while loop ends here
		// remember to print the count for the last value in the file
		std::cout << currVal << " occurs "
			<< cnt << " times" << std::endl;
	} // outermost if statement ends here
	return 0;
	}



Thing is, this code doesn't seem to work as intended. If I enter enough values, it breaks (stops counting values), and I don't understand why. I kinda prefer that I know how a program is expected to work before I dive into figuring out the code.

*Yes, I know most people recommend starting with a language simpler than C++.

ETA: judging by the exercises that follow, the authors intended this:

Exercises Section 1.4.4
Exercise1.17:What happens in the program presented in this section if the
input values are all equal? What if there are no duplicated values?
Exercise1.18:Compile and run the program from this section giving it only
equal values as input. Run it again giving it values in which no number is
repeated.
Last edited on
closed account (yR9wb7Xj)
I would tell you what helps, but you're pm is disable if you could enable it.
K PMs are enabled.
@Alpha22, hi can you please help me too? I'm literally in the same boat as @JQP lol.
How much is "enough"? Can you post example of series allowing to reproduce your problem?
Topic archived. No new replies allowed.