对齐ofstream的输出

Bil*_*ean 7 c++ fstream iostream

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;
}
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

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

das*_*ght 8

是的,<iomanip>header提供了setw操纵器,允许您设置输出的每个字段的宽度ostream.setw对每行使用操纵器而不是制表符可以更好地控制输出:

output << setw(25) << "Start time part 1 " << timeStr << " on " << dateStr << endl;
output << setw(25) << "Start time part 1000000 " << timeStr << " on " << dateStr << endl;
Run Code Online (Sandbox Code Playgroud)

要对齐左侧的字符串,请添加left操纵器:

output << left << setw(25) << "Start time part 1 " << timeStr << " on " << dateStr << endl;
output << left << setw(25) << "Start time part 1000000 " << timeStr << " on " << dateStr << endl;
Run Code Online (Sandbox Code Playgroud)

  • 请注意:虽然“std::setw”仅适用于*下一个*插入,但“std::left”会永久修改流。如果它是一个全局流,例如`std::cout`,一个行为良好的方法应该保存/恢复[`output.flags()`](https://en.cppreference.com/w/cpp/io/ios_base /flags),这样您的特定格式首选项就不会在程序的其他地方导致奇怪的结果。 (2认同)