gpt4 book ai didi

c++ - 将输出写入文件的不同列

转载 作者:行者123 更新时间:2023-11-30 03:04:45 24 4
gpt4 key购买 nike

您好,我想知道是否有任何函数库可以让我方便地执行此操作,或者您是否对我如何在不编写一行又一行代码的情况下优雅地执行此操作有任何建议(这是我最终使用 ofstream 所做的) ).

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

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

我用谷歌搜索没有得到任何有用的结果,感谢任何帮助:)

最佳答案

您的问题是对齐的表格输出,即视觉上有列,或者能够编写例如第四场,然后是第二场?

至于前者:最小的 C++ 解决方案使用 <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';
}

}

关于c++ - 将输出写入文件的不同列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8403099/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com