Search code examples
c++fstreamiomanipsetw

fstream and setw not aligning output properly


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;
}

Solution

  • 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.