c++ - 为什么我不能对ifstream对象使用getline()?

标签 c++ fstream

我想读取文件并写入副本文件,但是当我使用getline()函数时,在main函数中可以,但是在Writefile函数中可以。这让我感到困惑。
参数相同: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){

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

从概念上讲,当您从流对象读取或写入流对象时,它们会发生变化,因此不要对流对象使用const引用。

关于c++ - 为什么我不能对ifstream对象使用getline()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61793281/

相关文章:

c++ - wxSocket wxWidgets 失败

c++ - 如何在不重新创建现有文件的情况下写入 .txt 文件

c++ - std::fstream 不创建文件

c++ - 嵌套的 openMP 并行化结合 std::thread

c++ - 在极值中初始化浮点变量

c++ - CAD 系统用户界面的决策表示例

c++ - 使用 OpenGL 在圆圈中移动对象?

c++ - 如果不知道要读取的字符数,如何使用 fgets?

c++ - 模板函数在读取时返回错误值

c++ - 如何优雅地将字符串从 ifstream 复制到 vector<string>?