mercredi 11 août 2021

C++ why output is printing before i use end of line

#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" << '\n';
                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;
}

After compiling this code and running it.

i inputted 10 then enter then 50 then enter it prints a line and after using ctrl-z it prints 50 occurs 1 time. But i can't understand why it is printing 10 occurs 1 times before i pressed ctrl-Z. please tell the reason. And a way to print all of them after pressing ctrl-Z. I got this code from C++ Primer 5th Edition. using gcc 8.3.0. and using -std=c++0x in compiler flags

Aucun commentaire:

Enregistrer un commentaire