aligning output of ofstream

11,966

Solution 1

Yes, <iomanip> header provides the setw manipulator, letting you set the width of each field that you output to an ostream. Using setw manipulator for each row instead of tab characters would provide tighter control over the output:

output << setw(25) << "Start time part 1 " << timeStr << " on " << dateStr << endl;
output << setw(25) << "Start time part 1000000 " << timeStr << " on " << dateStr << endl;

To align strings on the left, add left manipulator:

output << left << setw(25) << "Start time part 1 " << timeStr << " on " << dateStr << endl;
output << left << setw(25) << "Start time part 1000000 " << timeStr << " on " << dateStr << endl;

Solution 2

int max_align = 10;
output << "Start time part 1 " << "\t" << timeStr 
<< std::string(max_align-timeStr.size(), " ") << " on " << dateStr << "\n";
Share:
11,966
BillyJean
Author by

BillyJean

I am very interested in programming (C/C++) and development, but I still have very much to learn. Feel free to contact me, if you have any tips for me.

Updated on June 04, 2022

Comments

  • BillyJean
    BillyJean almost 2 years

    I wish to output data from my program to a text file. Here is a working example showing how I do it currently, where I also include the date/time (I am running Windows):

    #include <iostream>
    #include <fstream>
    #include <time.h>
    
    using namespace std;
    
    int main()
    {
    
    char dateStr [9];
    char timeStr [9];
    
    _strdate(dateStr);
    _strtime(timeStr);
    
    ofstream output("info.txt", ios::out);
    output << "Start time part 1 " << "\t" << timeStr << " on " << dateStr << "\n";
    output << "Start time part 1000000 " << "\t" << timeStr << " on " << dateStr << "\n";
    output.close();
    
    
    return 0;
    }
    

    However the output of "info.txt" is not very readable to me as a user, since the time- and date stamp at the ends are not aligned. Here is the output:

    Start time part 1   15:55:43 on 10/23/12
    Start time part 1000000     15:55:43 on 10/23/12
    

    My question is, is there a way to align the latter part?