我对编程有点新,这里是我的问题。我需要做一个文本编辑器(像微软记事本,但更简单)。我试图做一步一步像第一我需要打开文件,然后阅读它等,但这段代码清除我的程序,我不能正确理解如何逐行读取它(可能使用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. – Rafalon
是的。谢谢先生。顺便说一句,我只是选择了一个随机数,我觉得这对我来说足够了,但是弦是更好的。谢谢 – AlexMIEL