使用 fstream 对象作为函数参数

Using fstream Object as a Function Parameter

本文关键字:函数 参数 fstream 对象 使用      更新时间:2023-10-16
#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)。