Hey guys (and girls), I'm trying to write a program that will read a simple text file and output a file with the same contents with the addition of line numbers. This is what I have so far:

#include<iostream>
#include<iomanip>
#include<fstream>
using namespace std;

int main()
{
char filename1[20],filename2[20], line[500];
int counter=1;
ifstream INSTREAM;
ofstream OUTSTREAM;

cout << "Please enter the name of the file you wish to modify: ";
cin >> filename1;
cout << endl;
INSTREAM.open(filename1,ios::in);

if(INSTREAM.fail())
{ cout << "ERROR: cannot open the file "<< filename1 << endl;
  return 1;
}

cout << "Please enter the name of modified file: ";
cin >> filename2;
cout << endl;
OUTSTREAM.open(filename2, ios::out);


while(!INSTREAM.eof())
{
INSTREAM.getline(line,500);
OUTSTREAM << counter << line;
counter++;
}

INSTREAM.close();
OUTSTREAM.close();
return 0;
}

In its current state the program needs to be forcefully terminated and it writes non stop to the new file. I need to figure out a way to get the input stream to read line by line which I am not currently able to do.

How about:

while( INSTREAM.getline(line,500) )
{
    OUTSTREAM << counter << line;
    counter++;
}

You can search on DaniWeb why the eof( ) usage is not advised.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.