循环中的setPrecision

Setprecision in a loop

本文关键字:setPrecision 循环      更新时间:2023-10-16
struct movie{
    int week;
    int month;
    int year;
    int rating;
};

在下面的循环中,我试图打印出结构向量中的所有信息,而我只想在评分中进行小数,但这使得它使得第一次迭代之后的所有线路都有小数。

for(int i = 0; i < info.size(); i++) {
    cout << info.at(i).week << endl;            
    cout << info.at(i).month << endl;
    cout << info.at(i).year << endl;
    cout << fixed << setprecision(2) << info.at(i).rating << endl;
}

有人知道我如何解决这个问题?

另外,如果我不使用指针并且没有分配动态内存,是否仍然有可能有内存泄漏?

它很乏味,但是您可以保存和还原格式标志

for(int i = 0; i < info.size(); i++) {
    cout << info.at(i).week << endl;            
    cout << info.at(i).month << endl;
    cout << info.at(i).year << endl;
    ios_base::fmt_flags save = cout.flags();
    cout << fixed << setprecision(2) << info.at(i).rating << endl;
    cout.flags(save);
}