std::format(),更好用的C++输出函数!!!

Aki 发布于 2022-10-19 193 次阅读


确实好用啊,为什么没有早点发现呢!!!

操了,之前写自定义对象输出的时候经常一大堆<<和“ ”,真的烦有时候。这个函数用起来真的舒服啊。

上代码:


class student
{
public:
    student(const string&name = "", const int& id = 0, const double& score = 0) :name(name), id(id), score(score) {}
    student(const student&rhs):name(rhs.name),id(rhs.id),score(rhs.score){}
    ~student()noexcept{}

    friend ostream& operator<<(ostream& os, const student& rhs)
    {
        os << "名字:" << rhs.name << "  " << "学号:" << rhs.id << "  " << "成绩:" << rhs.score; //老式的输出方式,一堆<<和""
        os << std::format("名字:{0}  学号:{1}  成绩:{2}", rhs.name, rhs.id, rhs.score);   //新版的输出方式,看着就舒服
        return os;
    }

private:
    string name;
    int id;
    double score;
};


int main()
{
    _CrtSetDbgFlag(33);
    std::ios::sync_with_stdio(false);
    cin.tie(NULL);
    
    student s("hello", 10, 20);
    cout << s << endl;
    return 0;
}

至于更多的用法请看这篇文章!!!写得很好!!!

std::format() - 知乎 (zhihu.com)