24.9k views
5 votes
Write a C++ pgm which Asks the user for the full path of a file to be read - path should include the folder and filename. Asks the user for the full path of a file to be written - path should include the folder and filename. Declares an array of strings of 1024 words. Opens the input and output files. Reads the file word by word into the array. Prints the content of the array in reverse order to both screen and output file at the same time. Remember : Check that input file opened successfully. Input file can be quite smaller than 1024 words, exactly 1024 words or much larger than 1024 words. Close the files before program ends. Put a 'pause' in your program before it ends.

User Indika
by
7.2k points

1 Answer

4 votes

Answer:

See explaination

Step-by-step explanation:

#include <iostream>

#include <fstream>

using namespace std;

int main()

{

int size = 10;

string inputFileName, outputFileName;

cout << "Please enter input file name, including full path: ";

cin >> inputFileName;

cout << "Please enter output file name, including full path: ";

cin >> outputFileName;

ifstream inFile(inputFileName.c_str());

ofstream outFile(outputFileName.c_str());

// checking whether input and output files are good to open

if(!inFile.is_open())

{

cout << "Cannot open " << inputFileName << endl;

exit(EXIT_FAILURE);

}

if(!outFile.is_open())

{

cout << "Cannot open " << outputFileName << endl;

exit(EXIT_FAILURE);

}

// declare an array of string to store 1024 words

string words[size];

// read the file for exactly 1024 words

// assuming each line of input file contains only 1 word

int count = 0;

string word;

while(getline(inFile, word))

{

if(count == size)

break;

words[count++] = word;

}

inFile.close();

// now we need to print the words array in reverse order both to the console and to the output file, simultaneously

cout << "WORDS:\\------\\";

for(int i = size - 1; i >= 0; i--)

{

if(words[i] != "")

{

cout << words[i] << endl;

outFile << words[i] << endl;

}

}

outFile.close();

system("pause");

return 0;

}

User Johan Paul
by
6.3k points