endl or \n ?

This is a discussion on endl or \n ? within the C++ Programming forums, part of the General Programming Boards category; Here's an example. Let's say you are debugging your code and trying to find out when it crashes. In some ...

  1. #16
    Registered User
    Join Date
    Jan 2005
    Posts
    7,344
    Here's an example. Let's say you are debugging your code and trying to find out when it crashes. In some cases (it is not guaranteed to happen all the time) the code below doesn't output anything. However, if you use endl instead of '\n', then it should always output the first i = 0 line before it crashes.
    Code:
    #include <iostream>
    #include <ostream>
    
    int main()
    {
      using namespace std;
    
      int i = 0;
      std::cout << "i = " << i << '\n';
    
      int *p = 0;
      *p = 3; // this might crash
    
      std::cout << "*p = " << *p << '\n';
    }
    All flushing means is sending output to the device. So if you are outputting to the console, then just because you say cout << i doesn't mean i is sent to the console right away. It is sent to an output buffer and when the system is ready or is forced to it flushes that output buffer to the console. Calling endl is one way to force it to flush the data to the console.
    Last edited by Daved; 08-24-2007 at 06:10 PM.

  2. #17
    Registered User
    Join Date
    Aug 2007
    Posts
    66
    Aha, OK. Thank you Daved and the rest members of the forum for helping. You guys, what are you using the most ? \n or endl ? Just wondering...

  3. #18
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Let's first explain the concept of "buffered output". You may think that if you do
    Code:
    cout << "a";
    an "a" appears on the output immediately. That is not the case - in fact, if you where to do something like this:
    Code:
    for(;;) {   // For-ever
      cout << "a";
      sleep(1);   // sleep for a second - can be replaced with a BIG empty loop if you like
    }
    The output of lots of "a" will not happen until several seconds later - a whole bunch of them all at once.

    This is for efficency: to call the OS to write something to an output-file (be it the console or a file such as "blah.txt") is "costly", whilst stuffing a few characters in a buffer is not very "expensive". So the C runtime tries to reduce the overhead of calling the OS until it's got enough data that it makes sense to do so.

    If we assume we have a buffered output, where the buffer is a few hundred bytes (and no "automatic flush", the following example would lead to a "blinking cursor with no output" - the system is waiting for your inptu of a number - but you wouldn't know that you should input the number, because the data is sitting in a buffer.
    Code:
        int num;
        cout << "Enter a number:\n";
        cin >> num;
    Nowadays, most C/C++ runtime libraries flush the cout/stdout stream before starting input, so the above code would "work correctly" for most cases. But if there wasn't a flush somewhere in the codepath up to the actual data input, then you wouldn't actually know what the program wants you to do, and it would just sit there waiting for a number to be inputted.

    --
    Mats

    Nowadays, most C/C++ libraries will implicitly do a flush() of the standard output when a call to read data IN is made - because it's quite often that this is "necessary".

  4. #19
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,048
    Nowadays, most C/C++ runtime libraries flush the cout/stdout stream before starting input, so the above code would "work correctly" for most cases.
    [...]
    Nowadays, most C/C++ libraries will implicitly do a flush() of the standard output when a call to read data IN is made - because it's quite often that this is "necessary".
    I think that that's part of the standard, actually; cout is flushed automatically when you use cin.
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  5. #20
    Registered User
    Join Date
    Jan 2005
    Posts
    7,344
    >> that's part of the standard, actually; cout is flushed automatically when you use cin.
    Exactly. Which is why an explicit flush is rarely needed.

    Another reason I now prefer '\n' is that to be technically correct, you have to #include <ostream> to use endl. There are no library implementations I know of that require this, but the standard doesn't guarantee endl will work without you including ostream. Since the flush is rarely needed, and I don't want to hassle with that technicality either, I just use '\n'.

  6. #21
    and the hat of sweating
    Join Date
    Aug 2007
    Location
    Toronto, ON
    Posts
    3,545
    No. I think it depends on the compiler and/or OS when something gets flushed automatically or when you need to explicitly flush it.
    Basically, if you reach a point in your code when you know the buffer must be flushed (like when some text must be displayed on the screen or written to a file), then just flush it, otherwise you won't know when or if it will be flushed.

  7. #22
    and the hat of sweating
    Join Date
    Aug 2007
    Location
    Toronto, ON
    Posts
    3,545
    BTW, my post was replying to the end of page 1 (5 posts up). Doh!

  8. #23
    Registered User
    Join Date
    Oct 2001
    Posts
    2,129
    another (ok small) reason is that endl requires another function call to operator<<.

  9. #24
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Quote Originally Posted by dwks View Post
    I think that that's part of the standard, actually; cout is flushed automatically when you use cin.
    That may be so, but I've certainly seen older/inferior compilers/C-libraries that didn't flush stdout on access to stdin - hence forcing one to use flush explicitly. But it's been quite a while since I last needed to use an explicit flush - I think I used it for some progress monitoring when writing to a large file some time ago (just outputting one '.') wouldn't really make the buffer flush.

    --
    Mats

  10. #25
    Registered User
    Join Date
    Sep 2006
    Posts
    835
    Quote Originally Posted by Daved View Post
    Another reason I now prefer '\n' is that to be technically correct, you have to #include <ostream> to use endl. There are no library implementations I know of that require this, but the standard doesn't guarantee endl will work without you including ostream.
    I came across this regarding whether there's a need to #include <istream> and/or <ostream> to use cin, cout, and/or endl.

    http://www.thescripts.com/forum/thread62138.html

    The claim is that this is an oversight in the standard, in which case one should expect that C++0x should fix it. Do you know if this is planned? If so, and if there are no current implementations which violate the expectation, then the best thing to do may be to just ignore the issue for the next 2 years, at which time the code will be 100% standards-compliant (as opposed to putting the headers in now and having them persist after the need goes away).

  11. #26
    Registered User
    Join Date
    Jan 2005
    Posts
    7,344
    I don't know for sure. comp.lang.c++.moderated and comp.lang.c++.std would be the newsgroups to search for that answer. You can also check the website for the current working draft, and if it is in there then it will almost surely stay. Someone linked to it on this site a little while ago but I don't know the exact URL at the moment.

  12. #27
    Registered User
    Join Date
    Jan 2005
    Posts
    7,344
    I have a copy of the 0xDraft and a copy of the 2003 version of the standard. I compared the two and there is this addition (in red) to the 0xDraft:
    Header <iostream> synopsis
    Code:
    \#include <ios>
    \#include <streambuf>
    \#include <istream>
    \#include <ostream>
    
    namespace std {
      extern istream cin;
      extern ostream cout;
      extern ostream cerr;
      extern ostream clog;
      extern wistream wcin;
      extern wostream wcout;
      extern wostream wcerr;
      extern wostream wclog;
    }
    So I would imagine that your solution would be fine. I would still generally use '\n' for the other reasons mentioned.

  13. #28
    Registered User
    Join Date
    Sep 2006
    Posts
    835
    That's good to know. It's reasonable to expect that just based on the names, <iostream> should be a superset of both <istream> and <ostream>.

  14. #29
    Registered User
    Join Date
    Nov 2006
    Posts
    519
    even scott meyers had trouble knowing the difference of endl and \n:

    http://www.aristeia.com/Papers/C++Re...s/novdec95.pdf

    the essence for people who don't want to read is: according to c++ standard cout (as well as cerr) is supposed to be unbuffered. so no flush is needed ever. just write to the stream and see the output and use \n or endl if you need a new line
    Last edited by pheres; 08-25-2007 at 02:15 AM.

  15. #30
    Registered User
    Join Date
    Aug 2007
    Posts
    66
    Well, guys I code something interesting (I think).

    Code:
    #include <iostream>
    
    using namespace std;
    
    int main()
    {
        char a,b;
        
        cout << "Type a char!\n";
        a = cin.get();
        cout << "Type another char!\n";
        b = cin.get();
        cout << "You printed " << a << b ;
        cin.get();
        
        return 0;
    }
    The output is so mysterius:
    [code]
    Type a char!
    a
    Type another char! //In this point it does NOT prompt me to type a char.
    You printed a

    I found that the solution is:
    Code:
    #include <iostream>
    
    using namespace std;
    
    int main()
    {
        char a,b;
        
        cout << "Type a char!\n";
        a = cin.get();
        fflush(stdin);
        cout << "Type another char!\n";
        b = cin.get();
        fflush(stdin);
        cout << "You printed " << a << b ;
        cin.get();
        
        return 0;
    }
    Another solution is:
    Code:
    #include <iostream>
    
    using namespace std;
    
    int main()
    {
        char a,b;
        
        cout << "Type a char!\n";
        a = cin.get();
        cin.ignore();
        cout << "Type another char!\n";
        b = cin.get();
        cin.ignore();
        cout << "You printed " << a << b ;
        cin.get();
        
        return 0;
    }
    Can you give me a solution with endl ? Because as you said before it flushes the output buffer. So lets see then.

Page 2 of 3 FirstFirst 123 LastLast
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. endl or \n ?
    By plain in forum C++ Programming
    Replies: 5
    Last Post: 09-01-2006, 02:50 PM
  2. endl - \n
    By Hugo716 in forum C++ Programming
    Replies: 8
    Last Post: 05-25-2006, 03:33 PM
  3. Endl - Undeclared identifier.
    By MipZhaP in forum C++ Programming
    Replies: 9
    Last Post: 03-03-2005, 11:01 AM
  4. endl vs \n
    By Chewbacca in forum C++ Programming
    Replies: 5
    Last Post: 09-08-2002, 01:42 PM
  5. "\n" or endl
    By itld in forum C++ Programming
    Replies: 2
    Last Post: 11-02-2001, 01:05 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21