使用fstream对象作为函数参数 [英] Using fstream Object as a Function Parameter

查看:239
本文介绍了使用fstream对象作为函数参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  #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<< 元音的数量:<< CTR;
}

main(){
fstream a;
a.open(temp.txt,ios :: in);
元音(a);
返回0;





$ b

在这个简单的程序中,我试图计算在文件temp.txt。但是,我收到错误消息:


ios :: ios(ios&)无法在函数
中访问fstream: :fstream(fstream&)

取而代之的是在函数中打开文件来完成这项工作。
为何如此?
非常感谢

注意:


如何通过函数参数使用fstream(特别是ofstream) / b>

这里说,它应该以我尝试的方式工作。



Rick

解决方案

fstream 对象不可复制。通过引用代替: fstream&
$ b

  void vowel(fstream& a)

请注意,您可以避免调用 open()通过向构造函数提供相同的参数:

  fstream a(temp.txt,ios :: in ); (!a.eof()) 

$ b $ p $并不使用 / code>,请立即检查读取操作的结果。只有当试图读取超出文件中最后一个字符时才会设置 eof()。这意味着当前面调用 get(ch)读取最后一行时,!a.eof()字符,但后续 get(ch)会失败并设置eof,但代码在处理完成之后才会注意到失败 ch



示例正确的结构:

  while(a.get(ch)){


#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;
}

In this simple program , I am trying t count the number of caps Vowels in the file temp.txt. However, I am getting the error:

ios::ios(ios &) is not accessible in function fstream::fstream(fstream&)

Instead opening the file in the function itself does the job. Why is it so? Thanks a lot

NB:

How do I use fstream (specifically ofstream) through a functions parameters

Here it says, that it should work the way I am trying.

Rick

解决方案

An fstream object is not copyable. Pass by reference instead: fstream&:

void vowel(fstream& a)

Note you can avoid the call to open() by providing the same arguments to the constructor:

fstream a("temp.txt", ios::in);

and don't use while(!a.eof()), check the result of read operations immediately. The eof() will only be set when an attempt is made to read beyond the last character in the file. This means that !a.eof() will be true when the previous call to get(ch) read the last character from the file, but subsequent get(ch) will fail and set eof but the code won't notice the failure until after it has processed ch again even though the read failed.

Example correct structure:

while (a.get(ch)) {

这篇关于使用fstream对象作为函数参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆