【问题标题】:Reading lines from text file and appear on screen [duplicate]从文本文件中读取行并出现在屏幕上[重复]
【发布时间】:2023-03-26 04:20:01
【问题描述】:

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

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

【问题讨论】:

  • 您是如何选择 4050 作为最大符号数的?我建议使用string 而不是char[],就像你在c++中一样,或者至少在你的代码中使用#define MAX_CHARS 4050并使用MAX_CHARS而不是4050,所以如果你需要改变你赢的值'不必寻找 4050 的每一次出现。
  • 确实如此。谢谢先生。顺便说一句,我刚刚选择了一个我觉得对我来说足够的随机数,但是是的,字符串更好。谢谢

标签: c++


【解决方案1】:

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

#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;
}

【讨论】:

  • 非常感谢!有用!但是,只要对您没有麻烦,您能解释一下吗?我的意思是“while(...)”的事情。
  • 只要给定条件为真,while 循环语句就会重复执行目标语句(写在 while 括号中)。在这种情况下,getline (myfile,line) 将在文件中没有更多行时返回 false,并且循环将终止。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-04-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多