1

setw does not seem to be aligning things here for me, and I can't figure out why that is. Inserting \t does push things to the right, but I'd like to have tighter control over the formatting of the output. Any ideas?

#include <iostream>
#include <fstream>
#include <iomanip>

using namespace std;

int main() {

    string name = "Name LastName";
    int age = 27;
    double milesRun = 15.5;

    ofstream outFile;
    outFile.open("text.txt");

    outFile << "Person's name: " << name << setw(12) << "Person's age: " << age << setw(12) << "Miles run: " << milesRun << endl;

    outFile.close();

    return 0;
}
Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
Blueshift
  • 160
  • 1
  • 6
  • 19
  • 3
    `setw` sets the (minimum) width of the next output. It doesn't consider earlier fields. – Bo Persson Oct 01 '15 at 06:34
  • 1
    Just think about using it as if you are building a table and using `setw` to define the cell size. I generally use `left` as well when trying to accomplish your goal. – badfilms Oct 01 '15 at 06:37

1 Answers1

2

Remember that when using setw, the function is used to declare the area that is about to appear. Therefore, you can use it to declare static values, such as the text in your information like "Person's Name:" by counting the characters and using that as your value (generally +1 or 2). Using that as an example, the value would be setw(16) to account for each character + 2 spaces. Then you apply another setw value to declare the field to come, choosing a value large enough to accommodate your data. Remember to align left so you can see how this affects your output. In your example, you were aligning right, and while that may give formatted output in some examples, it breaks in others, as you saw.


If you want more space between each data set, then simply increase the width of the field like in this example. This way everything is left aligned and you have no need for tabs.

badfilms
  • 4,317
  • 1
  • 18
  • 31
  • Thank you for clarifying this for me with an example, it's making more sense now. I've updated my example [here](http://cpp.sh/5hid) and it's ready to run. `setw` is working now, but I'm still missing something small in the alignment. Would you mind taking a quick look at it and letting me know? @badfilms @Bo Persson – Blueshift Oct 01 '15 at 08:42
  • So basically, as Bo Persson pointed out, `setw` sets the *minimum* width. In your case, you are exceeding the minimum because of the length of George Clooney's name. You can either a) increase the width value, or b) restrict the length of your data. – badfilms Oct 01 '15 at 09:03
  • Thank you so much for being so thorough with your examples and explanation. Answered exactly what I didn't understand. Thumbs up. – Blueshift Oct 01 '15 at 09:33