frerrr
frerrr

Reputation: 25

Why I could not use getline() with a ifstream object?

I want read a file and write a copy file.But when I use getline() function, it is OK in main function but not in Writefile function. It confused me. The parameters are same: getline(ifstream object,string)

#include<iostream>
#include<string>
#include<fstream>
using namespace std;

void Writefile(const ifstream & inF,ofstream & outF,const string &str);

int main(){
    ifstream inFile;
    inFile.open("Summary");
    ofstream outFile;
    string name = "SummaryCpy.txt";
    Writefile(inFile,outFile,name);
    string str22;
    getline(inFile,str22); //////good//////////
    return 0;
}

void Writefile(const ifstream & inF,ofstream & outF,const string &str){
    outF.open(str);
    if(! outF.is_open()){
        cout << "open file "<< str << " Erro" << endl;
        exit(EXIT_FAILURE);
    }
    string str1;
    while (inF.good()) {
        getline(inF,str1);  //////bad/////
        outF << str1 << endl;
    }
}

Upvotes: 1

Views: 80

Answers (1)

john
john

Reputation: 87959

void Writefile(const ifstream & inF,ofstream & outF,const string &str){

should be

void Writefile(ifstream & inF,ofstream & outF,const string &str){

Coceptually stream objects change when you read or write from them, so don't use const references for stream objects.

Upvotes: 2

Related Questions