7

我希望将数据从我的程序输出到文本文件。这是一个工作示例,显示了我当前的操作方式,其中还包括了日期/时间(我正在运行 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;
}

但是,作为用户,“info.txt”的输出对我来说不是很可读,因为末尾的时间和日期戳没有对齐。这是输出:

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

我的问题是,有没有办法对齐后半部分?

4

2 回答 2

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;

要在左侧对齐字符串,请添加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;
于 2012-10-23T14:04:56.417 回答
3
int max_align = 10;
output << "Start time part 1 " << "\t" << timeStr 
<< std::string(max_align-timeStr.size(), " ") << " on " << dateStr << "\n";
于 2012-10-23T14:05:21.473 回答