I need help reading lines from text files. I have been trying to read the first line just using getline(stream,line) assuming that my text file starts on the first line. This line of the text file is supposed to tell you how many lines there are so the next step I wrote while(x<= line) but I am unsure of how to read the 2nd or 3rd etc. line. Thanks in advance.

do
{
    buffer[0] = 0;
    strm.getline(buffer, BUF_SIZE);
    if (::strlen(buffer) > 0)
    {
        // Process buffer.
    }
}
while (!strm.eof() && !strm.bad());

Reading text file line by line :

#include <iostream.h>
#include <fstream.h>
#include <string.h>

void main ()
{
    string STRING ;
    ifstream infile ;
    infile.open ("file.txt") ;
        while(!infile.eof) // will run till End Of File
        {
            getline(infile,STRING) ; // Saves the line in STRING
            cout<<STRING ; // Prints our STRING
        }
    infile.close() ;
}

Edited 3 Years Ago by mridul.ahuja: correction

^^ That's not the correct way to do things. Most likely you're using a fossil compiler like turbo c. If you are ditch it for something like g++.

#include <string>
#include <iostream>
#include <fstream>
#include <sstream>

using namespace std;

int main()
{
    ifstream read ( "mytext.txt" );
    string line;

    while ( getline ( read, line, '\n' ) )
    {
        cout << line << endl;
    }
    cin.get();
    return 0;

}

The above code will work. Giving the following output after compilation and execution

x@x-Calistoga-ICH7M-Chipset:~/Documents/cpp$ g++ -Wall -pedantic test.cpp
x@x-Calistoga-ICH7M-Chipset:~/Documents/cpp$ ./a.out
hey there
this is 
a line of text

If you wanted to go a little further you could push those lines into either an array or std::vector (preferred).

Read text file from begining solution.

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main()
{
    fstream inputFile;
    string fileStr;
    string fileName = "file.txt";

    inputFile.open("file.txt");

    if(inputFile.is_open())
    {
        cout<<fileName<<" file is open."<<endl;

        inputFile.seekg(0, ios::beg);   //to start reading file from begining
        while(inputFile.good())         //just for safety
        {
            getline(inputFile, fileStr);    //read line from file and store it in fileStr
            cout<<fileStr <<endl;
        }
        inputFile.close();
    }
    else
        cout<<"Unable to open " <<fileName <<" file !" <<endl;

    return 0;
}
This article has been dead for over six months. Start a new discussion instead.