为什么C++中的getline()不起作用?(没有用于调用'getline(std :: ofstream&,std :: string&)'的匹配函数

JVE*_*999 1 c++ getline

我正在尝试从文件中读取,但C++不想运行getline().

我收到此错误:

C:\main.cpp:18: error: no matching function for call to 'getline(std::ofstream&, std::string&)'
          std::getline (file,line);
                                 ^
Run Code Online (Sandbox Code Playgroud)

这是代码:

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

using namespace std;

int main(){
    string line;

    std::ofstream file;
    file.open("test.txt");
    if (file.is_open())
     {
       while ( file.good() )
       {
         getline (file,line);
         cout << line << endl;
       }
       file.close();
     }


}
Run Code Online (Sandbox Code Playgroud)

0x4*_*2D2 7

std::getline设计用于输入流类(std::basic_istream),因此您应该使用std::ifstream该类:

std::ifstream file("test.txt");
Run Code Online (Sandbox Code Playgroud)

而且,使用while (file.good())循环中的输入条件通常是不好的做法.试试这个:

while ( std::getline(file, line) )
{
    std::cout << line << std::endl;
}
Run Code Online (Sandbox Code Playgroud)