0

So I am a complete beginner in C++. I am following the book C++ primer. The author always uses std::endl after every std::cout statement to flush the buffer. My quesion is should I always use std::endl?

#include<iostream>
int main()
{
    int sum=0,val=1;
    while(val<=10)
    {
        sum+=val;
        ++val;
    }
    std::cout<<"Sum of the 1 to 10 is: "<<sum<<std::endl;
    return 0;
}
  • Whether it should or should not be used depends entirely on rare, specific, application-specific details. 99.9% of the time it does not matter. – Sam Varshavchik Apr 01 '22 at 12:01
  • The cases where you should use `std::endl` are quite rare. – eerorika Apr 01 '22 at 12:03
  • You should use `std::endl` when you are done printing on the current line and want to move to the next line. It is perfectly ok to use several `std::cout << "something"` without `std::endl` if you want to put several different things on the same line. Note that depending on your terminal app, they may not display until you print the final `std::endl`. – Lev M. Apr 01 '22 at 12:03
  • 1
    @LevM. To end a line you can use `\n`. `std::endl` is to end a line **and** to flush the stream. Flushing the stream on every new line is not always desired – 463035818_is_not_an_ai Apr 01 '22 at 12:25
  • *My question is should I always use `std::endl`?* I never use `std::endl`, instead I used `"\n"`. If I really need to flush the buffer, I'll use `std::flush`. – Eljay Apr 01 '22 at 12:29

0 Answers0