lundi 23 novembre 2015

C++ Primer 1.4.4. Can't quite understand the need of first IF statement

I'm new here, so please, bear with me. I'm currently trying to learn c++ via C++ Primer 5th edition, and as I was looking at SO about a doubt I had on section 1.4.4 (which I managed to find the answer), I realized I don't understand the need or purpose of the first IF statement on this code:

#include <iostream>
int main()
{    
int currVal = 0, val = 0;

if (std::cin >> currVal) 
{
    int cnt = 1;  
    while (std::cin >> val) 
    { 
        if (val == currVal)   
            ++cnt;            
        else 
        { 
            std::cout << currVal << " occurs " << cnt << " times" << std::endl;
            currVal = val;    
            cnt = 1;          
        }
    }          
    std::cout << currVal <<  " occurs " << cnt << " times" << std::endl;
} 
return 0;
}

So I tried to change it in a way that looks more "logical" to me in order to try and understand the need for that IF, and ends up that the program seems to work exactly the same way...here's the modification:

#include <iostream>
int main()
{   
int currVal = 0, val = 0, cnt=1;    
std::cin >> currVal;         
    while (std::cin >> val) { 
        if (val == currVal) 
            ++cnt; 
        else { 
            std::cout << currVal << " occurs "
                << cnt << " times" << std::endl;
            currVal = val; 
            cnt = 1; 
        }
    }         
    std::cout << currVal << " occurs "
        << cnt << " times" << std::endl;     
return 0;
}

Can anybody be so kind and explain it for me? I would Appreciate it.

Aucun commentaire:

Enregistrer un commentaire