读取和显示文件

Reading and displaying a file

本文关键字:显示文件 读取      更新时间:2023-10-16

我在显示此文件时遇到问题。我正在尝试创建一个文件并将其显示在输出屏幕上。但是getline不起作用。它在第40行不断地给我一个"getline未声明"。我试过改变,但我做的都不管用。问题出在哪里?

#include <iostream>
#include <fstream>
#include <stdlib.h>
#include <string>

using namespace std;
int main()
{
  char filename[] = "Hello.txt";
  string line = "Hello, this is my output file";
  ofstream OutFile;
  OutFile.open(filename);
  if(OutFile.fail()) // check for successfully open ,
   {
     cout << "file named can not be found n";
     exit(1);
   } 
     OutFile << line;
     if (OutFile.is_open())
       OutFile.getline(line);
    OutFile.close();
     system("pause");
}

std::getline()是一个自由函数,而不是成员函数。成员函数版本适用于原始字符数组,由于您使用的是std::string,因此free函数是合适的。

std::getline(Outfile, line);

还要注意,std::getline()仅适用于std::istream类型的对象,并且由于您尝试执行输入,因此Outfile对象不应该是std::ofstream请将其更改为输入文件流std::ifstream

Outfile更改为std::fstream,这是一个双向文件流。