[英]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.我想读取一个文件并写入一个副本文件。但是当我使用 getline() function 时,在主 function 中可以,但在 Writefile ZC1C425268E68385D1AB5074C17A94F 中不行。 It confused me.
这让我很困惑。 The parameters are same:
getline(ifstream object,string)
参数相同:
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;
}
}
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.从概念上讲,stream 对象在您读取或写入对象时会发生变化,因此不要对 stream 对象使用 const 引用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.