setw(x) & endl;

This is a discussion on setw(x) & endl; within the C++ Programming forums, part of the General Programming Boards category; Code: #include <iostream> #include <iomanip> using namespace std; int i, j; int main() { cout << "12345"<< endl; cout << ...

  1. #1
    Registered User
    Join Date
    Oct 2009
    Posts
    29

    setw(x) & endl;

    Code:
    #include <iostream>
    #include <iomanip>
    using namespace std;
    
    
    int i, j; 
    
    
    int main()
    
    {
    cout << "12345"<< endl;
    cout << setw(7)<< endl;
    cout << "12345"<< endl;
    cout << "12345"<< endl;
    cout << "12345"<< endl;
    cout << setw(7)<< "K" << endl;
    cout << "12345"<< endl;
    cout << "12345"<< endl;
    cout << "12345"<< endl;
    
    return 0;
    
    }

    compiles this:

    Code:
    12345
    
      12345    
    12345
    12345
          K
    12345
    12345
    12345
    Press any key to continue . . .
    In the second box of code, the second set of numbers is indented 2 spaces which is equal to the setw(7). What I don't understand is why it does this. In the first box of code, just having cout << setw(7)<<endl; looks like it does a whole line skip and then continues to use the setw(7) on the next line after that endl; command. I would think the endl; would end any setw but it doesn't appear to. Is there a rule of why it does this?

  2. #2
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,185
    I believe the answer to this is that endl is a manipulator and not an object that is actually printed. Since you can "stack" manipulators, the setw doesn't take effect until the next actual print.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. endl or \n ?
    By BlackSlash12 in forum C++ Programming
    Replies: 38
    Last Post: 08-26-2007, 05:17 AM
  2. endl or \n ?
    By plain in forum C++ Programming
    Replies: 5
    Last Post: 09-01-2006, 01:50 PM
  3. Endl - Undeclared identifier.
    By MipZhaP in forum C++ Programming
    Replies: 9
    Last Post: 03-03-2005, 10:01 AM
  4. question about endl
    By hern in forum C++ Programming
    Replies: 7
    Last Post: 04-15-2004, 01:49 PM
  5. "\n" or endl
    By itld in forum C++ Programming
    Replies: 2
    Last Post: 11-02-2001, 12:05 AM

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