我有以下代码
void print(int & a, double & b, string & c)
{
cout << setprecision(2) << fixed;
const double GPA = a/b;
if(c == "Y")
{
cout << "\n\nTotal number of credit hours: " << a << endl;
}
else
{
cout << "\n*** Grades are being held for not paying the tuition. ***"
}
}
Run Code Online (Sandbox Code Playgroud)
如何cout在print(int, double, string)不篡改的情况下将in 写入文本文件print(int, double, string);?我试过这样的事
ofstream file;
file.open("file.txt");
file << print(a,b,c);
file.close();
cout << "file created" << endl;
Run Code Online (Sandbox Code Playgroud)
但这不编译.为什么不,我该如何解决?
你编写它的方式,你的print()功能不能输出到任何给定的流.这是因为它对其写入的流进行硬编码cout.
如果您希望它能够写入任何给定的流,则必须将该流参数化为另一个函数参数.对于(1)方便性和(2)与现有代码的兼容性假设print()只接受三个参数并写入cout,您可以通过将其默认为cout以下来使新参数成为可选:
void print(int& a, double& b, string& c, ofstream& os=cout) {
os << setprecision(2) << fixed;
const double GPA = a/b;
if (c == "Y") {
os << "\n\nTotal number of credit hours: " << a << endl;
} else {
os << "\n*** Grades are being held for not paying the tuition. ***";
}
}
Run Code Online (Sandbox Code Playgroud)
然后你可以按如下方式调用它:
print(a,b,c,file);
Run Code Online (Sandbox Code Playgroud)
您的代码无法编译的原因是您不能将void作为函数参数或操作符操作数传递.当函数声明为返回void时,这意味着它根本不返回任何内容.没有数据返回print()到流的流.流式传输发生在函数内部,因此只有您可以选择要写入输出的流.
| 归档时间: |
|
| 查看次数: |
1101 次 |
| 最近记录: |