我参加了C ++课程,但我不了解所提供的代码。问题是:如果我们只能改变输出的单个值的格式会很好,如下面的代码片段所示
Form gen4(4);
void f(double d){
Form sci8=gen4;
sci.scientific().setprecision(8);
std::cout << gen4(d) << " back to old options: "
<< d << std::endl;
}
gen4应该成为一种“类型”运算符,它将输出参数仅应用于单个输出操作。
我理解所询问的内容,并且我理解如何定义这样的自定义I / O操纵器:
Form gen4(4);
void f2(double d){
Form sci8=gen4;
sci8.scientific().setprecision(8);
std::cout << sci8 << d << endl;
// from now on, all output will use the format defined by sci8
// (until changed again)
}
所以我有2个问题。
答案 0 :(得分:0)
为了完整起见,我的回答是根据评论中给出的建议: form.h
#pragma once
#include <iostream>
class Form{
public:
int prc, wdt, fmt;
bool sci = false;
Form(int p=6) : prc(p) {
fmt=wdt=0;
}
Form& scientific() {
sci = true;
return *this;
}
Form& precision(int p) {
prc=p;
return *this;
}
Form& operator()(double d){
std::ios::fmtflags f(std::cout.flags());
if(sci){
std::cout.setf(std::ios_base::scientific);
std::cout.precision(prc);
}
std::cout << d;
std::cout.flags(f);
return *this;
}
};
std::ostream& operator<<(std::ostream& os, const Form& f){
return os;
}
的main.cpp
#include <iostream>
#include "include/form.h"
Form gen4(4);
void f(double d){
Form sci8=gen4;
sci8.scientific().precision(8);
std::cout << sci8(d) << " back to old options: " << d << std::endl;
}
int main() {
// Task1
f(64959.454243425);
return 0;
}
给出了预期的结果:
6.49594542e+04 back to old options: 64959.454
感谢Igor Tandetnik