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.
if(fin.fail( ))
{
cout << "Input file opening failed. \n";
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 == '\n') //Problems seem to begin at this point
{
fin.get(next);
cout << ++count << ": " << next;
fout << count << ": " << next;
> This program really aggravated me ... it seemed so easy, but I simply experienced an epic fail.
Do it step by step, one small step at a time, testing each step to make sure that it is working before you move on to the next step, and you would find that it is easy:
Step1 : read each line of text from a file and print the line to the screen
1 2 3 4 5 6 7 8 9 10 11
#include <iostream>
#include <fstream>
#include <string>
int main()
{
constchar* const path_to_file = __FILE__ ; // or "abcd.txt" or whatever
std::ifstream file(path_to_file) ;
std::string line ;
while( std::getline( file, line ) ) std::cout << line << '\n' ;
}
Step2: also print each line to another file
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#include <iostream>
#include <fstream>
#include <string>
int main()
{
constchar* const path_to_input_file = __FILE__ ; // or "abcd.txt" or whatever
constchar* const path_to_output_file = "output.txt" ;
std::ifstream fin(path_to_input_file) ;
std::ofstream fout(path_to_output_file) ;
std::string line ;
while( std::getline( fin, line ) )
{
std::cout << line << '\n' ;
fout << line << '\n' ;
}
}
Step3: To another file PRECEDED by a line number right-justified in a field of 3 spaces followed by a colon then 1 space, then the text of the line.