Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 973
DragonClaw Avatar asked Jan 24 '13 14:01

DragonClaw


People also ask

Can you pass ifstream as a parameter?

If you get an ifstream as parameter, it should be open from the start because you opened it outside your function. Passing a stream and then opening it inside your function does not make sense. Save this answer.

Can you pass an ofstream to a function?

Given that std::ofstream has a move constructor, it works to pass a temporary object to a function declared as void foo(std::ofstream) using e.g. foo(std::ofstream("file")) .

What is the difference between iostream and fstream?

An iostream is a stream which you can write to and read from, you probably won't be using them much on their own. An fstream is an iostream which writes to and reads from a file. So: every fstream is an iostream but not every iostream is an fstream.


2 Answers

You need to pass the fstream by reference:

void vowel(fstream& a){ .... }
//                ^ here!
like image 132
juanchopanza Avatar answered Oct 05 '22 01:10

juanchopanza


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)) {
like image 20
hmjd Avatar answered Oct 05 '22 01:10

hmjd