1.4.4. The if Statement

Like most languages, C++ provides an if statement that supports conditional execution. We can use an if to write a program to count how many consecutive times each distinct value appears in the input:

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

Get C++ Primer, Fifth Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.