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

标签 c++ linux

我尝试使用 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 阅读,而不是std::ofstream正如 Karoly 在评论中指出的那样。

关于c++ - 我如何从文件 C++ 中读取并输出它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11614542/

相关文章:

c++ - MSVC++ 2015 - SSE 编译器错误或程序中的错误/未定义行为?

c++ - 重载 R 值引用和代码重复

用于 Linux 的 C++ IDE,具有智能引用搜索

c++ - VIM YouCompleteMe 错误 - NoExtraConfDetected : No . 检测到 ycm_extra_conf.py 文件

c++ - 我的静态 map 总是空的

c++ - 如何以编程方式获取VS2017 Update 8.2中/permissive-设置的所有编译器标志

c++ - 来自 glGetError() 的 INVALID_ENUM 错误。 glGetError 与 glu、glew、glfw?

Linux目录权限读写不删除

linux - 将部分bash参数组合成一个字符串

c++ - 在 OpenCV 上使用 GPU 时如何确定线程数?