C++ Files / End of Line

Hi, i have a question about files in c++.

I need to do a program that reads a .txt file and stores it into a bidimentional character array and the show it in screen.

I have this code, but i dont know the conditional for the end of line in c++.
Basically i want to read a whole line and store it and then change the second index of the char matrix and read again, and so on, until the end of the file.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <fstream>
using namespace std;

int main() {
   char menu_art[150][60];
   ifstream fe("menu_art.txt");

   for(int i=0 ; (menu_art end of line) ; i++)
   {
              fe.getline(menu_art[][i],150);
   }


    for(int i=0 ; i < 60 ; i++)
       {
                  cout << menu_art[150][i] << endl;
       }

   return 0;
}


thanks
The call to getline() is its own end-of-file condition: like most other stream input operations, it returns a value which evaluates as true if the operation succeeded and as false if it failed (due to end of file, or some other error)

You're also apparently trying to read into columns of a 2D array. It's the rows that are contiguous.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <fstream>
using namespace std;

int main() {
   char menu_art[60][150]; // 60 1d-arrays, 150 chars each
   ifstream fe("menu_art.txt");

   int idx = 0;
   for( ; idx<60 && fe.getline(menu_art[idx], 150); ++idx)
   {
   }

   for(int i=0 ; i < idx ; i++)
   {
          cout << menu_art[i] << '\n';
   }
}


I think it's more sensible to use a vector of strings in this case:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <vector>
#include <string>
#include <iostream>
#include <fstream>
using namespace std;

int main() {
   vector<string> menu_art;
   ifstream fe("menu_art.txt");

   string line;
   while(getline(fe, line))
       menu_art.push_back(line);

   for(size_t i=0 ; i < menu_art.size(); ++i)
       cout << menu_art[i] << '\n';
}
Last edited on
Topic archived. No new replies allowed.