c++ - 从文本文件中读取行并显示在屏幕上

标签 c++

<分区>

我对编程有点陌生,这是我的问题。我需要做一个文本编辑器(类似于微软记事本,但更简单)。我试着一步一步地做,就像首先我需要打开文件,然后读取它等等。但是这段代码清除了我的程序,我无法正确理解我如何逐行读取它(可能使用 for 或 while)。谢谢

  #include <iostream>
#include <fstream>

using namespace std;

/*
void openFile()
{
    ofstream file2("text2.txt"); // create and open text file
    file2 << "Hello there"; // write in file
    file2.close(); // close file
}
*/

void readFile(char text[4050])
{

    ifstream file("text2.txt"); // read from file
    if (!file.is_open()) // if file is not opened then write "file is not found". else
        cout << "File is not found!" << endl;
    else
    {
        file.getline(text, 4050); // to where(text), max symbols(4050)
        cout << text << endl;
        file.close();
    }
}

using namespace std;

int main()
{

    char text[4050];

    ofstream file2("text2.txt");
    readFile(text);
    return 0;
}

我的代码可能是错误和奇怪的,但一旦我弄清楚如何修复它,我会尽力修复它。

最佳答案

这是逐行读取文件的最简单方法。

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main () {
  string line;
  ifstream myfile ("MyFile.txt");
  if (myfile.is_open()) {
    while ( getline (myfile,line) ) {
      cout << line << '\n';
    }
    myfile.close();
  }
  else {
    cout << "Unable to open file"; 
  }
  return 0;
}

关于c++ - 从文本文件中读取行并显示在屏幕上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43390313/

相关文章:

c++ - 使用适配器设计模式

c++ - 为什么返回子对象时 "that is the complete object of a subobject"对象的生命周期延长了?

c++ - CORBA : how does client poll from server?

c++ - 通过引用将对象参数传递给仿函数

c++ - 调试时找不到 "arm-elf-g++"

c++ - 未在指定位置绘制 Sprite

c++ - 如何以每秒 44100 次的速度计算用户定义的表达式

c++ - ifstream 没有返回正确的 int 值

c# - 在 RasDial 之后获取 IP 地址/接口(interface)号

C++: std::vector 两端保留空间