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

Write a C++ program that performs the following steps. 1. Read this file one tim

ID: 3594375 • Letter: W

Question

Write a C++ program that performs the following steps.

1. Read this file one time to determine how many records it contains. Be sure to check for a successful file open here.

2. Close the file.

3. Allocate memory dynamically to store the data from step 1. This dynamically allocated memory should be for an array of strings.

4. Reopen the file and read it a second time, storing each record into the array of strings from step 3.

5. Print the first and last record in the array.

6. Release the allocated memory.

7. Your program output should look like this:

Date    Open    High    Low    Close    Volume    Adj Close*
Oct 16, 2015    64.26    64.26    64.26    64.26    0    60.18

Explanation / Answer

#include <fstream>

#include <iostream>

#include <string>

int main()

{

std :: string data; /* to store the current data */

std :: string *lines; /* hold all the lines memory allocated dynamically */

ifstream inFile; /* input file */

int i =0; /* maintaining the line numbers */

int num_lines = 0

inFile.open( "filename.txt",ios::in );

/* looping to count the num of lines */

while ( !inFile.eof())

{

inFile >> data;

if( data == " " )

num_lines = num_lines + 1;

}

/* dynamically allocating the memory */

lines = new std::string[num_lines];

/* moving the file to starting / beginning */

inFile.seekg( 0, ios::beg );

/* looping to extract data line by line to string array */

while( !inFile.eof() )

{

inFile >> data ;

if(data == " ")

i = i+1;

else

lines[i] = lines[i] + data;

}

/* printing first and last lines */

std :: cout << lines[ 0 ];

std :: cout << lines[ num_lines -1 ];

/* closing the file */

inFile.close();

return 0;

}

/* thank you! Hope this helps */

/* if any doubts, please comment */

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote