【发布时间】:2022-01-21 01:14:29
【问题描述】:
【问题讨论】:
-
所以你问的是如何写入文件?
-
来自How do I ask a good question?:“请勿发布代码、数据、错误消息等的图片 - 将文本复制或输入到问题中"
标签: c++ string file-handling
【问题讨论】:
标签: c++ string file-handling
这是一个建议:
#include <cstdint>
#include <string>
#include <vector>
#include <iostream>
#include <iomanip>
struct DataPoint {
std::string date;
uint64_t cases;
uint64_t deaths;
uint64_t recovered;
uint64_t newtoday;
};
using DataVector = std::vector<DataPoint>;
DataVector readFromDatabase() {
DataVector vec;
vec.push_back( {"01/12/2021", 1285631, 28745, 1242718, 414} );
vec.push_back( {"01/12/2021", 1285631, 28745, 1242718, 414} );
vec.push_back( {"01/12/2021", 1285631, 28745, 1242718, 414} );
vec.push_back( {"01/12/2021", 1285631, 28745, 1242718, 414} );
vec.push_back( {"01/12/2021", 1285631, 28745, 1242718, 414} );
return vec;
}
int main() {
DataVector data = readFromDatabase();
std::cout << std::setw(10) << "Date"
<< std::setw(11) << "Cases"
<< std::setw(11) << "Deaths"
<< std::setw(11) << "Recovered"
<< std::setw(11) << "New Today" << std::endl;
for ( const DataPoint& d : data ) {
std::cout << std::setw(10) << d.date
<< std::setw(11) << d.cases
<< std::setw(11) << d.deaths
<< std::setw(11) << d.recovered
<< std::setw(11) << d.newtoday << std::endl;
}
return 0;
}
结果:
Date Cases Deaths Recovered New Today
01/12/2021 1285631 28745 1242718 414
01/12/2021 1285631 28745 1242718 414
01/12/2021 1285631 28745 1242718 414
01/12/2021 1285631 28745 1242718 414
01/12/2021 1285631 28745 1242718 414
【讨论】:
只使用字符串格式。 \n - 换行和 \t - 制表符
string text = "header 1 \t header 2 \t header 3 \n column 1 \t column 2 \t column 3 \n";
输出看起来很漂亮
header 1 header 2 header 3
column 1 column 2 column 3
更新: 正如在 cmets 中所说,您还可以在值之间添加分隔符。像 ',' 或 '^' 等...并将其保存为 *.csv 文件。担心你会得到你想要的行和列,但前提是你用一些 csv 阅读器打开文件。此外,正因为如此,您可以轻松地再次将它们从文件中拆分出来
【讨论】:
\t 将在屏幕上占用多少空间。这是正在写入的控制台的属性。不同的间距配置,再加上正在写入的可变长度字符串,可能会弄乱您的对齐方式。