Search code examples
c++ifstream

Using ifstream's getLIne C++


Hello World,

I am fairly new to C++ and I am trying to read a text file Line by Line. I did some research online and stumbled across ifstream.

What is troubling me is the getLine Method. The parameters are istream& getline (char* s, streamsize n );

I understand that the variable s is where the line being read is saved. (Correct me if I am wrong)

What I do not understand is what the streamsize n is used for.

The documentation states that:

Maximum number of characters to write to s (including the terminating null character).

However if I do not know how long a given line is what do I set the streamsize n to be ?

Also,

What is the difference between ifstream and istream ?

Would istream be more suitable to read lines ? Is there a difference in performance ?

Thanks for your time


Solution

  • You almost never want to use this getline function. It's a leftover from back before std::string had been defined. It's for reading into a fixed-size buffer, so you'd do something like this:

    static const int N = 1024;
    char mybuffer[N];
    
    myfile.getline(mybuffer, N);
    

    ...and the N was there to prevent getline from writing into memory past the end of the space you'd allocated.

    For new code you usually want to use an std::string, and let it expand to accommodate the data being read into it:

    std::string input;
    
    std::getline(myfile, input);
    

    In this case, you don't need to specify the maximum size, because the string can/will expand as needed for the size of the line in the input. Warning: in a few cases, this can be a problem--if (for example) you're reading data being fed into a web site, it could be a way for an attacker to stage a DoS attack by feeding an immense string, and bringing your system to its knees trying to allocate excessive memory.

    Between istream and ifstream: an istream is mostly a base class that defines an interface that can be used to work with various derived classes (including ifstream objects). When/if you want to open a file from disk (or something similar) you want to use an ifstream object.