Output stream alignment

I want to output data from my program to a text file. Here is a working example showing how I am doing this 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 for me as a user, since the time and date stamp on the ends is not aligned. Here is the result:

 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 last part?

+6
source share
2 answers

Yes, the <iomanip> header provides a setw manipulator, allowing you to set the width of each field that you ostream to ostream . Using the setw manipulator for each line instead of tabs will 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 the lines to the left, add the 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; 
+7
source
 int max_align = 10; output << "Start time part 1 " << "\t" << timeStr << std::string(max_align-timeStr.size(), " ") << " on " << dateStr << "\n"; 
+2
source

All Articles