Using fstream Object as a Function Parameter

前端 未结 3 1453
误落风尘
误落风尘 2020-12-16 01:58
#include 
#include 
#include 

void vowel(fstream a){
    char ch;
    int ctr = 0;
    while(!a.eof()){
        a         


        
相关标签:
3条回答
  • 2020-12-16 02:34

    You need to pass the fstream by reference:

    void vowel(fstream& a){ .... }
    //                ^ here!
    
    0 讨论(0)
  • 2020-12-16 02:52

    try this. instead of sending the file count the vowels in line.

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

    if you want to pass the file then use the above ans.(pass fstream by reference).

    0 讨论(0)
  • 2020-12-16 02:55

    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)) {
    
    0 讨论(0)
提交回复
热议问题