int main () {
int num1, num2;
int cnt = 1;
if (cin >> num1){
while (cin >> num2){
if (num1==num2){
++cnt;
} else {
cout << num1 << " is " << cnt << " times" << endl;
cnt = 1;
num1 = num2;
}
}
}
cout << num1 << " is " << cnt << "-times" << endl;
}
This code accepts a line of numbers and outputs how many times each number was entered. What I dont understand is why there is num1=num2. With removing it program outputs the first number which was entered, which lead me to believe that I don't know how cin works in loops.
What I think now is that first digit goes into if (cin >> num1), and it keeps sitting here and next same digits don't overwriting num1 integer. Second and the rest digits going into while (cin >> num2) overwriting it every time until there is a different number, which makes else to execute and it outputs number which was stored in num1 the whole time.
With num1=num2 it changes num1 in if(cin>> num1) and the whole thing starts again.
Am I right?
Which also strange that the very last cout may sure inside of first if body, and it may not, it works anyway...
Edit1: with num1=num2; I input 1 1 2 2 3 3 3, as one line, it outputs
1 is 2 times
2 is 2 times
3 is 3 times.
Without num1=num1;
1 is 2 times
1 is 1 times
1 is 1 times
1 is 1 times
1 is 1 times