Why use <<std::endl; if /n after the statement is much simpler?

std::cout << “Welcome to Bulls and Cows\n”;

VS

std::cout << “Welcome to Bulls and Cows” << std::endl;

Hi Kim

I’ve done a little research on this as I wondered why Ben used endl in the videos and my understanding of them is that endl flushes the output buffer whereas \n does not. Using endl will send the output immediately to the screen which could come in handy if for example your code was just about to perform some time consuming operation and you wanted to make sure that a message was displayed before doing so; whereas with \n in the same situation there could be a slim chance that the message may not get to the screen in time.

In the Bulls and Cows game it makes sense to use the endl to make sure the message is on the screen before any user input is accepted through cin.

Due to the flush endl is slightly slower than \n but unless you are outputting a lot (and I mean a lot) of text then there should not be an issue.

I hope that helps.

Mike

Privacy & Terms