read lines from text file

Hi All,

I have learnt how to read lines out of a text file by doing the following:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#define MAX_LINE_LEN    512


void main()
{
   string fname("myfile.txt");
   ifstream fin(fname.c_str());
   char line[MAX_LINE_LEN];

   while (fin.good())
   {
      fin.getline(line, MAX_LINE_LEN);
      cout << line << endl;
   }

   fin.close();
}


This works well, but was just wondering if there are versions of ifstream that can getline into a string class so that I don't have to know the size of a max line length before hand.

I realize that there aren't really situations where defining MAX_LINE_LEN large enough won't work, but was just wondering if such a version of reading a line does exist.
instead of getline, you could try something like,

1
2
3
4
5
6
7
8
while (fin.good()) {
    string line = "";
    char ch = 0;
    while (fin.get(ch) != '\n') {
        line.push_back(ch);
    }
    cout << line << endl;
}
there are classes cpecialized for string stream.
headername is <sstream>
class names are:
ostringstream, istringstream, striingstream.

objects of those classes are capable of reading/writing into/from strings.
Thank you Mooncabbage.

I had to make some changes to your snippet, but got the general idea:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
void main()
{
   string fname("myfile.txt");
   ifstream fin(fname.c_str());

   while (fin.good())
   {
      string line = "";
      char ch = 0;
      while (!fin.eof() && ch != '\n')
      {
         fin.get(ch);
         if (!fin.eof() && ch != '\n')
            line += ch;
      }
      
      cout << line << endl;
   }

   fin.close();
}


I'm not sure if I am doing this as effeciently as could be, so did try your suggestion codekiddy but don't understand how to use this class in context of the ifstream class.

I was hoping I could simply try fin.getline(sline)

where sline is of type istringstream or ostringstream.

Do you have an example for me in this context that demonstrates use of these classes to achieve desired result.
All "versions of ifstream" can getline into a string class.

Example, with a few other touch-ups

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
   string fname("myfile.txt");
   ifstream fin(fname.c_str());
   string line;

   while (getline(fin, line))
   {
      cout << line << endl;
   }
}
Thanks Cubbi, this works very well.

I didn't realize that these version's of getline was available.

I only knew of the methods of the stream class.
Topic archived. No new replies allowed.