使用 fstream 对象作为函数参数
Using fstream Object as a Function Parameter
#include <iostream.h>
#include <fstream.h>
#include <stdlib.h>
void vowel(fstream a){
char ch;
int ctr = 0;
while(!a.eof()){
a.get(ch);
if (ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U'){
cout << ch;
ctr++;
}
}
cout << "Number of Vowels: " << ctr;
}
main(){
fstream a;
a.open("temp.txt", ios::in);
vowel(a);
return 0;
}
在这个简单的程序中,我尝试计算文件temp.txt中的大写元音数量。但是,我收到错误:
ios::ios(iOS &) 在函数中无法访问 fstream::fstream(fstream&)
相反,在函数本身中打开文件可以完成这项工作。为什么会这样?多谢
铌:
如何通过函数参数使用 fstream(特别是 ofstream)
这里它说,它应该按照我正在尝试的方式工作。
瑞克
fstream
对象不可复制。改为通过引用传递: fstream&
:
void vowel(fstream& a)
请注意,您可以通过向构造函数提供相同的参数来避免对open()
的调用:
fstream a("temp.txt", ios::in);
并且不要使用while(!a.eof())
,立即检查读取操作的结果。仅当尝试读取文件中最后一个字符以外的字符时,才会设置eof()
。这意味着,当上一次调用 get(ch)
从文件中读取最后一个字符时,!a.eof()
为 true,但后续get(ch)
将失败并设置 eof,但代码直到再次处理ch
后才会注意到失败,即使读取失败。
示例正确的结构:
while (a.get(ch)) {
您需要
通过引用传递fstream
:
void vowel(fstream& a){ .... }
// ^ here!
试试这个。 而不是发送文件计数元音在行中。
#include <iostream.h>
#include <fstream.h>
#include <stdlib.h>
int vowels=0;
void vowel(string a){
char ch;
int ctr = 0;
int temp=0;
for(temp=0,temp<a.length();temp++){
ch=a.at(temp);
if (ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U'){
cout << ch;
ctr++;
}
}
vowels+=ctr;
}
main(){
fstream a;
a.open("temp.txt", ios::in);
string temp;
while(getline(a,temp))
{
vowel(temp);
function2(temp);
function3(temp);
... so on for more then one functions.
}
vowel(a);
return 0;
}
如果要传递文件,请使用上面的 ans.(通过引用传递 fstream)。
相关文章:
- static_assert在宏中,但也可以扩展到可以用作函数参数的东西
- C++中的高效循环缓冲区,它将被传递给C样式数组函数参数
- 当从函数参数中的临时值调用复制构造函数时
- 如何从"decltype()"获取函数参数的数量<funtion>?
- 如何将lambda作为模板类的成员函数参数
- 模板参数推导失败,函数参数/参数不匹配
- 如何在C++中将迭代器作为函数参数传递
- 将函数参数"const char*"转换为"std::string_view"是
- C++ 如何将数组值解压缩为函数参数
- 主函数参数的属性
- 具有两个间接寻址运算符 (C++) 的函数参数的用途
- "Warning: Comma within array index expression"但逗号分隔函数参数
- 如何定义在用作函数参数时工作的类模板的转换
- 将函数参数完美转发到函数指针:按值传递呢?
- 为什么我不能将引用作为 std::async 的函数参数传递
- 什么..(省略号)作为函数原型中唯一的函数参数,C++?
- 是否可以就地构造一个固定大小的数组作为函数参数?
- 接受模板作为函数参数
- 将成员函数作为构造函数参数调用时出错 "Variable is not a type name"
- Arduino 函数参数