Question

C++ create a program that: in main: -opens the file provided for input (this file is...

C++

create a program that:

in main:

-opens the file provided for input (this file is titled 'Lab_HW10_Input.txt' and simply has 1-10, with each number on a new line for 10 lines total)

-calls a function to determine how many lines are in the file

-creates an array of the proper size

-calls a function to read the file and populate the array

-calls a function to write out the contents of the array in reverse order

*output file should be named 'reverse_output.txt'

Homework Answers

Answer #1

Following is the required code and it's been written in Code::Blocks IDE:

The code BEGINS from here:

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

using namespace std;

// SIGNATURES of the required functions
int lines (ifstream&);
void populate (ifstream&, int []);
void rvrsArrWrite (ofstream&, int [], int);

// MAIN FUNCTION
int main()
{
int filesize;

// Opening file streams to input and output files
ifstream inputFile("Lab_HW10_Input.txt");
ofstream outputFile("reverse_output.txt");

// If input file is not found
if(inputFile == NULL){
cout << "File Does Not Exist!";
exit(0);
}

// call to function lines() and assigning the returned value to 'filesize'
filesize = lines(inputFile);
cout << "Number of lines in the file: " << filesize << endl;

// To make the pointer go back to the beginning of the file
inputFile.clear();
inputFile.seekg(0, ios::beg);

// creating an array of proper size
int arr[filesize];

// call to function populate()
populate(inputFile, arr);

// Elements in the array
cout << "Following are the elements in the array: " << endl;
for(int i = 0; i < filesize; i++){
cout << arr[i] << " ";
}

// call to the function rvrsArrWrite()
rvrsArrWrite(outputFile, arr, filesize);

// Closing the File Streams
inputFile.close();
outputFile.close();

cout << endl;
return 0;
}

// Function lines() - to determine the number of lines in the file
// @param ifstream& - a reference to the file input stream variable
int lines (ifstream &file){

string tname;
int len = 0;
// stores the number of lines in the file
while (std::getline(file, tname)) {
len++;
}
return len;

}


// Function populate() - to read the file and populate the array
// @param ifstream& - a reference to the file instream variable
void populate(ifstream &file, int arr[]){

int temp; // to temporarily store the data from the file, for each line
int i = 0; //for indexing of array
while(file>>temp){
arr[i] = temp;
i++;
}
cout << "\nThe array has been populated Successfully!" << endl;

}

// Function rvrsArrWrite() - to write the contents of array to a file in reverse order
// @param ofstream& - a reference to the file outstream variable
// @param int [] - integer array to be reversed and written to file
// @param int - size of the array
void rvrsArrWrite(ofstream &file, int arr[], int length){

// Looping through each element in the array and writing it to the file
for(int i = length-1; i >= 0; i--){
file << arr[i] << endl;
}
cout << "\n\nWriting to the file named \"reverse_output\" is done Successfully!" << endl;
cout << "Please open the file in a text editor to check its contents..." << endl;

}

The code ENDS here!

Some KeyPoints about the program:

  • The method used to count the number of lines in the file is very simple. First we declare an integer variable int the function lines(), named len, and set its value to 0. We go through each line in the file and increment the value of filesize by 1. And at the end of the function, we return the value of len.
  • After this we assign the variable filesize with the returned value of len and use this variable filesize to declare an array of appropriate size with the statement as shown below:

int arr[ filesize ];

  • One thing that would, perhaps, confuse you in the program is the use of the following statements:

inputFile.clear();
inputFile.seekg(0, ios::beg);

These statements are very necessary inn this program. Allow me to explain why? After using the funtion, lines(), we read the file and as the pointer finishes reading the last data in the file, it sets the eof (End of File). Then if we hadn't used the above statements and try to use the file again in populate() function, it would have read nothing, because the pointer is already at the end. So these two statements clear the eof flag and sends the pointer back to the starting of the file.

  • the rvrsArrWrite() function reads each element of the array starting from the last (lenth-1)th and reaching the 0th element and writing each element to the file "reverse_output.txt" during the process.

Following is a ScreenShot of the sample data in the 'Lab_HW10_Input.txt' file:

This is the Screenshot of the Output for a Test Run for above input file:

And here is the ScreenShot of the "reverse_output.txt" file after the program executed:

Hope the code meets all your requirements.

Best Wishes!

Know the answer?
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for?
Ask your own homework help question
Similar Questions
Lab 6    -   Program #2   -   Write one number to a text file. Use the write()...
Lab 6    -   Program #2   -   Write one number to a text file. Use the write() and read() functions with binary                                                        data, where the data is not char type.              (Typecasting is required) Fill in the blanks, then enter the code and run the program. Note:   The data is int type, so typecasting is            required in the write() and read() functions. #include <iostream> #include <fstream> using namespace std; int main() {    const int SIZE = 10;   ...
Write C++ code to: Create a function called “ReadFile” that: Accepts a filename as input Opens...
Write C++ code to: Create a function called “ReadFile” that: Accepts a filename as input Opens the file for reading Reads an integer from the file and returns it. Create a main function that Asks the user to input a file Passes that file to the “ReadFile” function Prints the returned integer to the screen Extra Credit: Set a default argument of “intfile.txt” for the “ReadFile” function Write an overloaded function of “ReadFile” that accepts two filenames and reads an...
WRITE C++ PROGRAM FOR 1,2,3,4 PARTS of question, DO ADD COOMENTS AND DISPLAY THE OUTPUT OF...
WRITE C++ PROGRAM FOR 1,2,3,4 PARTS of question, DO ADD COOMENTS AND DISPLAY THE OUTPUT OF A RUNNING COMPILER QUESTION: 1) Fibonacci sequence is a sequence in which every number after the first two is the sum of the two preceding ones. Write a C++ program that takes a number n from user and populate an array with first n Fibonacci numbers. For example: For n=10 Fibonacci Numbers: 1, 1, 2, 3, 5, 8, 13, 21, 34, 55 2): Write...
Create a Python program that opens and reads a csv file. Display csv file in legible...
Create a Python program that opens and reads a csv file. Display csv file in legible format. Include the program as a function.
Create a Python program that opens and reads an excel file (xlsx). Display excel file in...
Create a Python program that opens and reads an excel file (xlsx). Display excel file in legible format. Include the program as a function.
LANGUAGE C The codes below reads another .c or .txt file. Then, it will read the...
LANGUAGE C The codes below reads another .c or .txt file. Then, it will read the contents of every line and store the contents into a string array. Example: .c file that is to be read: #include <stdio.h> int main(){    printf("Hello World");    return ; } _______________(END OF THE FILE)_______________ Therefore, the code will read the contents above and store the contents in every line into an array, such that.... array[0] = "#include <stdio.h>\n" array[1] = "\n" array[2] ="int...
Write a Java Program, that opens the file "students.txt" The program must read the file line...
Write a Java Program, that opens the file "students.txt" The program must read the file line by line The program parses each line that it reads For example, for this line: 1:mohamed:ali:0504123456:cs102:cs202 The program must print    >ID = 1    >First Name = Mohamed   >Last Name = Ali   >Mobie = 0504123456   >Courses = cs102, cs202 In addition, it adds the mobile phone number into an ArrayList called studentPhoneList Print the content and the size of studentPhoneList Show your results and provide...
Write an assembly program that reads characters from standard input until the “end of file” is...
Write an assembly program that reads characters from standard input until the “end of file” is reached. The input provided to the program contains A, C, T, and G characters. The file also may have new line characters (ASCII code 10 decimal), which should be skipped/ignored. The program then must print the count for each character. You can assume (in this whole assignment) that the input doe not contain any other kinds of characters.  the X86 assembly program that simply counts...
write a c++ program that can take an input file with string as for example "i...
write a c++ program that can take an input file with string as for example "i saw 5 teddy bears" and in a created output file create a new string to just change a digit to a word. To " I saw five teddy bears" . output should be located in an output file thank you
Create a C Program called Summer_Heat that meets the following criteria: Lines 1,2: Identifies the name...
Create a C Program called Summer_Heat that meets the following criteria: Lines 1,2: Identifies the name of Program that the Programmer Lines 4,5: Includes the header files to allow input and output and use the system commands Line 7: Includes Declarations comment Line 8: Declares counter as an integer with an initial value of 0 Line 9: Initializes a double array called temperature using a single statement and the following 10 values 78.6 82.1 79.5 75.0 75.4 71.8 73.3 69.5...
ADVERTISEMENT
Need Online Homework Help?

Get Answers For Free
Most questions answered within 1 hours.

Ask a Question
ADVERTISEMENT