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:
#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.