我如何从文件C++中读取并输出它

How do i read from a file C++ and output it

本文关键字:读取 输出 C++ 文件      更新时间:2023-10-16

我尝试使用getline

但它给了我一些错误

注意:__ssize_t getline(char**,size_t*,FILE*)

我的线路就像这个

ofstream myfile;
myfile.open("file.txt");
while(!myfile.eof())
{
    getline(myfile,sline);
    cout << sline;
 }

如何让我的C++读取file.txt

确保您有#include <string>,其中定义了std::getline(),并且slinestd::string

将循环结构更改为:

while (std::getline(myfile, sline))
{
    std::cout << sline << "n";
}

以避免处理失败的读取。

使用std::ifstream阅读,而不是Karoly在评论中指出的std::ofstream

看起来像是#include d <stdio.h><cstdio>,因此正在尝试使用C的getline函数。更改:

getline(myfile,sline);

至:

std::getline(myfile,sline);

以确保您正在使用C++CCD_ 11。