Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 387
Lemyr Avatar asked Dec 28 '25 04:12

Lemyr


2 Answers

In case of an empty input or non numerical input, your second version will print

std::cout << currVal << " occurs "
    << cnt << " times" << std::endl;

With currVal having a value of 0 and a count of 1, which is wrong.

See: operator>>

like image 128
fjardon Avatar answered Dec 30 '25 18:12

fjardon


std::cin >> currVal is an expression that returns an istream reference.

The istream has an implicit conversion to bool provided by an overloaded operator. This evaluates to false if there are no more data to be read.

The if is exploiting that. If you omit this then your program will not run correctly since currVal will be set to zero.

like image 22
Bathsheba Avatar answered Dec 30 '25 19:12

Bathsheba



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!