从文本文件中读取行并显示在屏幕上
Reading lines from text file and appear on screen
我对编程有点陌生,这是我的问题。我需要做一个文本编辑器(类似于微软记事本,但更简单(。我试图一步一步地做,就像首先我需要打开文件,然后阅读它等等。但是这段代码清除了我的程序,我无法正确理解如何逐行阅读它(可能使用 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;
}
相关文章:
- Winapi:屏幕截图未显示在窗口中
- 如何在快板的屏幕中显示子位图的绘制?
- SFML 中的字体.信息不显示在屏幕上.显示的不是信息,而是点
- 如何使用 openGL 在屏幕上显示加载的纹理
- 如何使用方法覆盖在输出屏幕上显示堆栈整数值
- 如何使用TouchGFX在LCD屏幕上显示ADC值
- 为什么屏幕上显示了一半的三角形
- 如何在屏幕上显示对象列表?
- C++列出屏幕以在第二台显示器中显示图像
- 显示和隐藏Windows 10屏幕键盘(osk.exe)时遇到问题
- 将25个甚至整数存储到一个名为intlist的整数阵列中,然后在屏幕上显示数组,并在屏幕上显示名为fivintegers
- QML强制窗口将在第一个屏幕上显示
- 如何使用OpenGL在屏幕上显示三角形
- 从文本文件中读取行并显示在屏幕上
- 我的程序没有将字符显示在屏幕上
- 在屏幕上显示矢量
- 在同一屏幕上显示两个不同的对象
- 屏幕显示脚本中'.'令牌之前的预期非限定 id
- C / SFML:使用两个递归调用在屏幕上打印凸形形状仅显示第一个递归调用中的形状,而不是第二个
- 如果我使用的是迭代器,为什么在c++中没有屏幕显示呢