【问题标题】:Append string after other string after few space? [closed]在几个空格之后在其他字符串之后附加字符串? [关闭]
【发布时间】:2022-01-21 01:14:29
【问题描述】:

我想通过 c++ 中的文件处理在 myFile 上写入,就像数据库中的数据存储(行和列形式)。像这样:

【问题讨论】:

标签: c++ string file-handling


【解决方案1】:

这是一个建议:

#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

天箭:https://godbolt.org/z/5nec8Y1hT

【讨论】:

    【解决方案2】:

    只使用字符串格式。 \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 阅读器打开文件。此外,正因为如此,您可以轻松地再次将它们从文件中拆分出来

    【讨论】:

    • 这仅在您对所有值进行硬编码时才有效。
    • 好吧。作者可以将其保存为 csv 文件,只需在值之间使用拆分器,但这可能不是他想要的,但我会添加这个来回答,谢谢
    • 您无法始终控制\t 将在屏幕上占用多少空间。这是正在写入的控制台的属性。不同的间距配置,再加上正在写入的可变长度字符串,可能会弄乱您的对齐方式。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-24
    • 2015-03-22
    • 2014-05-10
    • 1970-01-01
    • 1970-01-01
    • 2018-08-31
    相关资源
    最近更新 更多