Reading lines from text file

Hello, i am kinda new to programming and here is my question. I need to do a text editor(something like microsoft notepad but more simple). Im trying to do it step by step like first i need to open file, then read it and etc. But this code clears my programme and i cant properly understand how do i read it line by line(probably using for or while). Thanks
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
  #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;
}


My code is probably wrong and weird but i'll try my best to fix it once i figure it out how.
Better use std::string and that getline():

http://www.cplusplus.com/reference/string/string/getline/?kw=getline

The loop would be very simple:
1
2
3
4
        while(file.getline(text, 4050)) // Note: if end of file is reached (or any other error) this expression will return false otherwise true
        {
          cout << text << endl;
        }
One way to read a file line by line
1
2
3
4
5
6
7
8
9
10
11
12
13
  ifstream src("YourFileName");
  if (!src)
  {
    perror("Error opening file ");
    system("pause");
    return -1;
  }
  string line;
  while (getline(src, line))
  {
    // use line
     cout << line << "\n";
  }
Topic archived. No new replies allowed.