将输出写入文件的不同列

Writing output to different columns of a file

本文关键字:文件 输出      更新时间:2023-10-16

嗨,我想知道是否有任何函数库可以让我方便地做到这一点,或者如果你有任何建议,我如何才能优雅地做到这一点,而不需要编写一行又一行的代码(这就是我最终用ofstream做的)。

Loop over i
   Loop over j
      Evaluate f(i*alpha,j);
      Write f to column i;

就像这样。我需要比较一个QM问题的100个不同的特征函数,我宁愿不为每个值写一个文件,也会使绘图更容易。

我做了谷歌没有任何可用的结果,感谢任何帮助:)

你的问题是对齐的,表格输出,即视觉上有列,或者能够写,例如第4个字段,之后第二个?

对于前者:Minimal c++ solution使用<iomanip> .

假设你有:

#include <iostream>
#include <vector>
#include <iomanip>
struct Date     { int year, month, day;
                  Date(int year, int month, int day)
                      : year(year), month(month), day(day) {}
                };
struct Time     { int hour, minute, second;
                  Time (int hour, int minute, int second)
                      : hour(hour), minute(minute), second(second){}
                };
struct Birthday { Date date;
                  Time time;
                  Birthday (Date date, Time time)  : date(date), time(time) {}
                };
std::ostream& operator<< (std::ostream &ofs, Time const &rhs) {
    using std::setw;
    return ofs << std::setfill('0')
               << setw(2) << rhs.hour << ':'
               << setw(2) << rhs.minute << ':'
               << setw(2) << rhs.second;
}
std::ostream& operator<< (std::ostream &ofs, Date const &rhs) {
    using std::setw;
    return ofs << std::setfill('0')
               << setw(4) <<  rhs.year << '-'
               << setw(2) << rhs.month << '-'
               << setw(2) << rhs.day;
}
std::ostream& operator<< (std::ostream &ofs, Birthday const &rhs) {
    return ofs << rhs.date << ' ' << rhs.time;
}

struct Dude {
    std::string first_name;
    std::string last_name;
    Birthday    birthday;
    Dude (std::string const &f, std::string const &l, Birthday const &b)
        : first_name(f), last_name(l), birthday(b) {}
};

然后你可以输出一个简单的表,像这样:

int main () {
    using std::setw;
    std::vector<Dude> d;
    d.push_back (Dude("John", "Doe",        Birthday(Date(1980,12,11),Time(6,45,0))));
    d.push_back (Dude("Max",  "Mustermann", Birthday(Date(1980,12,11),Time(6,45,0))));
    std::cout << std::left;
    // Output a fancy header.
    std::cout << std::setfill(' ')
              << setw(24) << "<last name>" << "| "
              << setw(16)  << "<first name>" << "| "
              << "birthday" << 'n';
    // Data output follows. Note: No lines of lines and code.
    for (std::vector<Dude>::iterator it=d.begin(), end=d.end(); it!=end; ++it) {
        std::cout << std::setfill(' ')
                  << setw(24) << it->last_name << "| "
                  << setw(16) << it->first_name << "| "
                  << it->birthday  << 'n';
    }
}

如果您的算法允许您这样做,请重构循环以按行编写:

Loop over j {
    Loop over i {
        Evaluate f(i*alpha, j);
        Write f to column i, <TAB>;
    }
    Write <CR><LF>
}