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?
是的,<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)
| 归档时间: |
|
| 查看次数: |
10724 次 |
| 最近记录: |