简体   繁体   English

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

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

I tried to use getline 我尝试使用getline

but it give me some error 但这给我一些错误

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

My line is like this 我的线是这样的

ofstream myfile;

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

How do i get my C++ to read file.txt 我如何让我的C ++读取file.txt

Ensure you have #include <string> , where std::getline() is defined, and that sline is a std::string . 确保您具有#include <string> ,其中已定义std::getline() ,并且该slinestd::string

Change the structure of the loop to: 将循环的结构更改为:

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

to avoid processing a failed read. 以避免处理失败的读取。

Use std::ifstream to read, not std::ofstream as pointed out by Karoly in the comments. 使用std::ifstream读取,而不要使用Karoly在注释中指出的std::ofstream

It looks like you #include d <stdio.h> or <cstdio> and are therefore trying to use C's getline function. 看起来您#include d <stdio.h><cstdio> ,因此正在尝试使用C的getline函数。 Change: 更改:

getline(myfile,sline);

to: 至:

std::getline(myfile,sline);

to ensure that you are using the C++ getline . 确保您使用的是C ++ getline

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM