1

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.

2
Contributors
1
Reply
2
Views
7 Years
Discussion Span
Last Post by vmanes
0

How about:

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

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

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.