Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

I seem to be missing a concept or 2 here ... I am tasked with writing a program

ID: 3537679 • Letter: I

Question

I seem to be missing a concept or 2 here ... I am tasked with writing a program that reads text from a file and outputs each line to the screen as well as to another file PRECEDED by a line number ...

in addition, I have to Print the line number at the start of the line and right-adjusted in a field of 3 spaces ...

Follow the line number with a colon then 1 space, then the text of the line.

Another kicker, is I have to grab the data 1 character at a time and write code to ignore leading blanks on each line.

Here is what I have so far:

#include <iostream>
#include <conio.h>
#include <fstream>
#include <string>
#include <cstdlib>
#include <cctype>

using namespace std;

int main()
{
char next;
int count = 0;

ifstream fin;
fin.open("myFile.txt");

ofstream fout;
fout.open("newFile.txt");

if(fin.fail( ))
{
cout << "Input file opening failed. ";
system ("pause");
exit(1); // exit the program
}
cout << ++count << ": ";
fout << count << ": ";

//read in the lines one character at a time
while(!fin.eof() && fin.get(next))//until the end of the file is reached
{
if(next == ' ') //Problems seem to begin at this point
{
fin.get(next);
cout << ++count << ": " << next;
fout << count << ": " << next;

if(!isalpha(next))
{
fin.get(next);
}
else
{
cout << ++count << ": " << next;
fout << count << ": " << next;
}

}

cout << next;
fout << next;
}

fin.close();
fout.close();

getch();
return 0;
}

Any help would be greatly appreciated.

Explanation / Answer

#include <iostream>

#include <fstream>

#include <iomanip>

/* #include <conio.h> - If on windows */


using namespace std;


int main() {

int lineNumber = 1;


ifstream inputFile("myFile.txt");

ofstream outputFile("newFile.txt");


// Status variable to indicate the starting point in a line

bool startOfLine = true;


while (inputFile.good()) {

char ch = inputFile.get(); // Get a character from the input file


// Skip spaces at the start of line

if (startOfLine == true && ch == ' ') { continue; }

// Print the prefix

cout << setw(3) << lineNumber << ": " << ch;

outputFile << setw(3) << lineNumber << ": " << ch;


// Read the rest of the line and copy to screen & file

while (inputFile.good()) {

ch = inputFile.get();


cout << ch;

outputFile << ch;


// Proceed to next line on encountering newline character

if (ch == ' ' || ch == ' ') break;

}


lineNumber++;

}


inputFile.close();

outputFile.close();


/* getch(); - If on windows */

return 0;

}


// Ping me if you have any doubts! Glad to help!